標籤:函數指標 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++函數指標