1、解釋
(1)函數指針指向的是函數而非對象;和其他指針一樣,函數指針指向某種特定類型;
(2)函數的類型由它的返回類型和形參類型決定,與函數名無關;
2、聲明
bool lengthCompare(const string &, const string &)
(1) bool (*pf) (const string &, const string &);
(2) using F=int(int* , int);
(3) typedef decltype(lengthCompare) *FuncP2
(4) typedef bool Func(const string&, const string&)
3、初始化
pf = lengthCompare;
pf=&lengthCompare;
pf = 0;
4、調用:形參和返回類型必須完全匹配
bool b1 = pf("hello", "goodbye");
bool b2 = (*pf)("hello", "goodbye");
bool b3 = lengthCompare("hello", "goodbye");
5、重載函數的指針:編譯器通過指針類型決定選用哪個函數;精確匹配;
void ff(int *);
void ff(unsigned int);
void (*fn)(unsigned int) = ff;
6、函數指針形參:不能定義函數類型的形參,跟數組一樣,會自動轉換
void useBigger(const string &s1, const string &s2, bool pf(const string&, const string&)); //自動轉換為函數指針
void useBigger(const string &s1, const string &s2, bool (*pf)(const string&, const string&));
7、類型別名
(1) typedef bool Func(const string&, const string&);//函數類型
(2) typedef decltype(lengthCompare) Func2;//函數類型
(3) typedef bool(*FuncP)(const string&, const string&); //函數指針
(4) typedef decltype(lengthCompare) *FuncP2;// decltype的結果是函數類型
void useBigger(const string &s1, const string &s2, Func2);
8、返回函數指針
(1) using F= int(int*, int);
F *f1(int) ;
(2) using PF=int(*)(int* ,int)
PF f1(int) ;
(3) int (*f1 (int))( int*, int);
(4) 尾置返回類型的方式
auto f1(int) -> int(*)(int*, int);
(5)decltype簡化函數返回類型