C++之函数指针
(1)函數指針的聲明
所謂函數指針是指指向函數而非對象的指針,這個指針所指向的函數的類型由返回類型和參數表確定,與函數名無關。例如:
bool (*pf)(const string& a, const string& b);pf是一個指向函數的指針,該函數的形參是兩個const string&類型的字符串,返回值是一個bool類型的值。需要注意的是上面的聲明中不等價于下面的寫法:
bool *pf(const string& a, const string& b);因為上面是一個普通的函數聲明,它的形參也是兩個const string&類型的字符串,返回值是一個指向bool對象的指針,函數名為pf。
(2)函數指針的初始化和賦值
這里首先使用typedef簡化函數指針的定義:
typdef bool (*pf)(const string&, const string&);對函數指針的初始化有三種方式:
a. 0值常量表達式
pf myPf1 = 0;b. 直接飲用函數名或者在函數名上應用取地址操作符
1 bool compareLength(const string& sa, const string& sb); 2 pf myPf1 = compareLength; 3 pf myPf2 = &compareLength; View Codec. 同類型的函數指針
myPf2 = myPf1;(3)通過函數指針調用函數
指向函數的指針可以通過解引用符調用函數,也可以直接調用它所指向的函數:
(4)函數指針作為形參
函數指針可以作為形參,具體的使用方式有兩種:第一種是直接以函數類型的形式作為形參,這種形式下編譯器隱式地把它當做指向該函數類型的函數指針;第二種是顯示的傳遞一個指向某個函數類型的函數指針。例如:
(5)函數指針作為返回類型
函數指針也可以作為一個函數的返回類型,但是不同與函數指針作為形參的情形:函數類型可以作為形參,但不可以做返回類型,只能將指向函數的指針作為返回類型。例如:
上面的代碼表示函數ff需要一個int類型的參數,返回一個指向函數類型為int(int*, int)函數指針。也可以借助typedef定義如下:
typedef int (*pf)(int*, int); pf ff(int);(6)指向重載函數的函數指針
C++語言允許使用函數指針指向重載的函數:
1 extern void ff(vector<double>); 2 extern void ff(unsigned int); 3 4 void (*pf)(unsigned int) = ff; View Code函數指針指向重載的函數時,指針的類型必須與重載函數的一個版本精確匹配,否則對該指針的初始化或賦值都會導致編譯錯誤!
(7)示例代碼?
1 #include "stdafx.h" 2 3 #include<iostream> 4 using namespace std; 5 6 #include<string> 7 #include<vector> 8 9 typedef int (*PF)(const string&, const string&); 10 int compareLength(const string& s1, const string& s2) 11 { 12 if(s1.length() > s2.length()) 13 { 14 return 1; 15 } 16 return (s1.length() == s2.length() ? 0 : -1); 17 } 18 19 //函數指針作為形參 20 const string& GetLonger(const string& s1, const string& s2, int (*pf)(const string&, const string&)) 21 { 22 int res = pf(s1,s2); 23 if (res == 1) 24 { 25 return s1; 26 } 27 return s2; 28 } 29 30 const string str_cat(const string& s1, const string& s2) 31 { 32 string s = s1 + s2; 33 return s; 34 } 35 36 //函數指針作為返回類型 37 const string (*GetPf(const string& s1, const string& s2))(const string&, const string&) 38 { 39 const string (*pf)(const string& s1, const string& s2) = str_cat; 40 return pf; 41 } 42 43 //函數指針指向重載的函數 44 void ff(vector<int>) 45 { 46 cout<<"overload function 1"<<endl; 47 } 48 49 void ff(int a) 50 { 51 cout<<"overload function 2"<<endl; 52 } 53 54 int _tmain(int argc, _TCHAR* argv[]) 55 { 56 PF comPf = compareLength; 57 string s1("hello"); 58 string s2("hell"); 59 60 //函數指針調用函數 61 int compareRes1 = comPf(s1,s2); 62 int compareRes2 = (*comPf)(s1,s2); 63 cout<<compareRes1<<" "<<compareRes2<<endl; 64 65 //函數指針作為形參 66 const string getS1 = GetLonger(s1,s2,comPf); 67 cout<<getS1<<endl; 68 69 //返回函數指針 70 const string (*getPf)(const string& s1, const string& s2) = GetPf(s1, s2); 71 string catRes = getPf(s1,s2);//調用返回的函數指針 72 cout<<catRes<<endl; 73 74 //指向重載函數的函數指針 75 void (*ofunc)(int) = ff; 76 ofunc(3); 77 78 system("pause"); 79 80 return 0; 81 } View Code??
以上整理自C++ Primer中文版第四版 7.9 節。
?
轉載于:https://www.cnblogs.com/sophia-yun/archive/2013/06/07/3124038.html
總結
- 上一篇: POJ 计算几何入门题目推荐
- 下一篇: C/C++中的段错误(Segmentat