C++學習基礎十七-- 函數指標

來源:互聯網
上載者:User

標籤:方式   ret   amp   表示   文法   指標   返回   str1   定義   

C++常用的函數指標

文法:傳回值類型 (*函數名)(參數列表);


舉例說明:int (*Func)(int m, int n);

  • 用typedef簡化函數指標的定義

        例如:

1 typedef int (*Func)(int m, int n);
  • 函數指標的初始化和賦值
 1 // 1. 先聲明對應函數指標類型的函數   2 int max(int num1, int num2) 3 { 4    return num1 > num2 ? num1 : num2; 5 } 6  7 //2. 初始化 8 Func fc = 0;//表示函數指標不指向任何函數 9 Func fp = max;//表示函數指標指向max函數10 11 //3. 調用12 max(10,20);//直接調用13 fp(10,20);//使用函數指標調用
  • 指標函數可以作為形參

         有兩種方式:

1 //1.2 void useBigger(const string &str1, const string &str2,3                 bool (const string &s1, const string &s2));4 //或者5 void useBigger(const string &str1, const string &str2,6                 bool (*)(const string &s1, const string &s2));
  • 返回指向函數的指標

        例如:

1 int (*ff(int)) (int *p1, int n);

 

這句話的意思是:ff(int)是一個函數,帶有一個int型形參,傳回值類型為int (*) (int *p1, int n),也就是返回一個函數指標。使用typedef可使該定義更簡明易懂:

1  typedef int (*PP)(int *p1, int n); 2  PP ff(int);

 

  • C++允許函數指標指向重載的函數

        例如:

1 extern void ff(vector<double> vds);2 extern void ff(unsigned int n);3 4 typedef void (*PF1)(unsigned int n);5 6 PF1 p = ff;//ff(unsigned int)

指標的類型必須與重載函數的其中一個版本精確匹配,否則導致編譯出錯。

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.