C++ 函數指標

來源:互聯網
上載者:User

1 、函數指標的定義

int (*fp)(int a);//定義了一個指向函數的指標

int *fp(int a);//錯誤,這是一個返回整形指標的函數了,而不是函數指標。

int _tmain(int argc, _TCHAR* argv[]){//////////////////////////////////////////////////////////////////////////Example1cout << FuncTestMethod <<endl; //輸出函數地址  int (*fPtr)(int i);//定義函數指標fPtr = FuncTestMethod;//;//將函數FuncTestMethod的地址賦給函數指標fPtrcout << fPtr(5) << " | " << (*fPtr)(15) <<endl;//上面的輸出fp(5),這是標準c++的寫法,(*fp)(15)這是相容c語言的標準寫法,兩種同意,但注意區分,避免寫的程式產生移植性問題! //////////////////////////////////////////////////////////////////////////Example2cout << FuncTestMethod <<endl; //輸出函數地址typedefint (*fPtr)(int i);//定義函數指標類型,類型名為fPtr。typedef定義可以簡化函數指標的定義 fPtr f;//這裡利用自己定義的類型名fPtr定義了一個f的函數指標! f = FuncTestMethod;//;//將函數FuncTestMethod的地址賦給函數指標fPtrcout << fPtr(5) << " | " << (*fPtr)(15) <<endl;//上面的輸出fp(5),這是標準c++的寫法,(*fp)(15)這是相容c語言的標準寫法,兩種同意,但注意區分,避免寫的程式產生移植性問題! return 0;}int FuncTestMethod(int i){return i;}

  

2、函數指標所指向的函數,必須為全域函數或類的靜態函數

class FuncPtr{typedef int (*func)(void);public:void FuncPtrTet(func func1){(*func1)();};static int display(void){cout <<"display"<<endl;return 0;}};

  

int display2(void){cout <<"display2"<<endl;return 2;}

  實現

int _tmain(int argc, _TCHAR* argv[]){FuncPtr f;f.FuncPtrTet(FuncPtr::display);f.FuncPtrTet(display2);return 0;}

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.