標籤:方式 ret amp 表示 文法 指標 返回 str1 定義
C++常用的函數指標
文法:傳回值類型 (*函數名)(參數列表);
舉例說明:int (*Func)(int m, int n);
例如:
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);
例如:
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++學習基礎十七-- 函數指標