無參函數指針的聲明和調用
#include <iostream> int func1() { return 1; } int main() { int (*ptrFunc)(); ptrFunc = func1; std::cout<<(*ptrFunc)(); return 0; }
運行以上代碼,控制檯輸出1。
第8行 函數指針的聲明。int對應函數返回類型。
第9行 指針的賦值。
第10行 函數指針的調用。不要漏了後面的一對括號。
帶參數的函數指針的聲明和調用
#include <iostream> int add(int a, int b) { return a + b; } int main() { int (*ptrFunc)(int, int); ptrFunc = add; std::cout<<(*ptrFunc)(1,2); return 0; }
運行以上代碼,控制檯輸出3。
第8行 相比上一段代碼,同樣是函數指針的聲明,第2個括號中多了2個int,這對應函數的參數。
別名typedef
函數指針的聲明比較複雜,通常爲它起個別名。
typedef int(*LPFUNCADD) (int,int); //返回類型(*別名) (參數1, 參數2)
函數指針的定義可以簡寫成這樣。
LPFUNCADD ptrFunc;
完整代碼如下
#include <iostream> int add(int a, int b) { return a + b; } typedef int(*LPFUNCADD) (int,int); //返回類型(*別名) (參數1, 參數2) int main() { LPFUNCADD ptrFunc; ptrFunc = add; std::cout<<(*ptrFunc)(1,2); return 0; }