C&C++函數指標

來源:互聯網
上載者:User

標籤:函數指標   c++函數指標   

今天在閱讀libcurl的源碼的時候,發現裡邊定義函數指標的方法,與平時自己所用方式有所不同。詳細分析了一下。

libcurl的代碼中,定義了一組發送資料的函數指標。如下所示:

//代碼目錄: lib/urldata.hstruct connectdata {......Curl_send *send[2];......};
其中,Curl_send定義如下:
//代碼目錄: lib/urldata.h/* return the count of bytes sent, or -1 on error */typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */                            int sockindex,            /* socketindex */                            const void *buf,          /* data to write */                            size_t len,               /* max amount to write */                            CURLcode *err);           /* error to return */

感到疑惑的是,平時我們要使用typedef定義函數指標的話,一般都是寫成下面形式:
//定義一個函數指標,所指向函數接收一個整形參數,並返回整形值。typedef int (*pFunc)(int);
但是,curl_send的定義中,並沒有帶上指標符號。在查閱一些資料後,發現這樣的定義方法也是可以的。

於是,寫了下面的程式驗證了一下。

#ifdef __cplusplus#include <iostream>#else#include <stdio.h>#endifint testFunc(int para){#ifdef __cplusplusstd::cout << "C++ parameter is: " << para << std::endl;#elseprintf("C parameter is: %d\n", para);#endifreturn 0;}int main(){typedef int (pTestFunc)(int);pTestFunc *pFunc = testFunc;   //方式1:ok·pFunc(1111);                   //方式2:ok(*pFunc)(2222);                //方式3:okpTestFunc *pFunc2 = &testFunc; //方式4:okpFunc2(3333);return 0;}
如果將上面程式儲存為C程式檔案(.c),進行編譯,得到下面運行結果:
C parameter is: 1111
C parameter is: 2222
C parameter is: 3333

如果儲存為C++程式檔案(.cpp),得到運行結果:
C++ parameter is: 1111
C++ parameter is: 2222
C++ parameter is: 3333

從上面結果可以看到:
1.採用與curl_send相同的函式宣告方式,也是可以的。如上面的pTestFunc的定義。
2.對於函數指標pFunc的初始化,不管採用哪種方式都是可以的。參考上面的方式1與方式4。
3.而對於函數指標pFunc的調用,也可以採用不同的方式,參考方式2與方式3。

當然,我們也採用傳統的函數指標聲明方式,如下程式所示:

int main(){typedef int (*pTestFunc)(int);pTestFunc pFunc = testFunc;   //方式5:okpFunc(1111);                  //方式6:ok(*pFunc)(2222);               //方式7:okpTestFunc pFunc2 = &testFunc; //方式8:okpFunc2(3333);return 0;}
運行結果與前面所述完全相同。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

C&C++函數指標

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.