5分鐘搞懂C++函式指標與函式型別
函式指標和函式型別
函式指標指向的是函式而非物件。和其他指標型別一樣,函式指標指向某種特定型別。
函式型別由它的返回值和引數型別決定,與函式名無關。
bool length_compare(const string &, const string &);
上述函式型別是:
bool (const string &, const string &);
上述函式指標pf:
bool (*pf)(const string &, const string &);
使用函式指標
當把函式名作為一個值使用時,該函式自動的轉換成指標,如:
pf = length_compare <=>等價於 pf = &length_compare12
函式指標形參
函式型別不能定義為形參,但是形參可以是指向函式的指標;
函式作為實參使用時,會自動的轉換成函式指標;
typedef bool Func(const string &, const string &) // Func是函式型別; typedef bool (*FuncP)(const string &, const string &) // FuncP是函式指標型別; typedef decltype(length_compare) Func2// Func2是函式型別; typedef decltype(length_compare) *Func2P // Func2P是函式指標型別;
注意decltype(length_compare)返回的是函式型別,而不是函式指標型別;
using FTtype = int(int,int); //函式型別 typedef int (*pf)(int, int); //函式指標 int func(int a, int b){return a+b;} void print(int a, int b, FTtype fn){ // 編譯器將其隱式轉化成函式指標 cout << fn(a,b) << endl; } int main() { print(1,2,func); cout << typeid(FTtype).name() << endl; cout << typeid(func).name() << endl; cout << typeid(decltype(func)).name() << endl; cout << typeid(pf).name() << endl; return 0; }
下面兩個宣告語句是同一個函式,因為編譯器會自動的將FTtype 轉換成函式指標型別。
void print(int a, int b, FTtype fn);
void print(int a, int b, pf fn);
返回指向函式的指標
雖然不能返回一個函式,但是能返回執行函式型別的指標。和函式引數不同,編譯器不會自動地將函式返回型別當作指標型別處理,必須顯示的將返回型別指定為指標。如:
using F = int(int*, int); using PF = int(*)(int*,int); Ff1(int);//錯誤: F是函式型別 PFf1(int);//正確: PF是函式指標型別
f1也可以寫出下面兩種形式:
int (*f1(int))(int*, int);
auto f1(int)->int(*)(int*, int);
作者:guoxiaojie_415
來源:https://blog.csdn.net/guoxiaojie_415/article/details/79921788
原文釋出時間為:2018-09-30
原文作者:良許Linux
本文來自雲棲社群合作伙伴“ ofollow,noindex">良許Linux ”,瞭解相關資訊可以關注“ 良許Linux ”。