指向函數(shù)的指針必須指定指針指向什么類型的函數(shù)。
聲明應該識別函數(shù)的返回類型和函數(shù)的參數(shù)列表。
聲明應提供與函數(shù)原型相同的功能相同的信息。
假設我們有以下函數(shù)。
double my_func(int); // prototype
下面是一個適當指針類型的聲明:
double (*pf)(int);
pf指向一個使用一個int參數(shù)并返回類型double的函數(shù)。
我們必須把括號圍繞* pf提供適當?shù)倪\算符優(yōu)先級。
括號的優(yōu)先級高于*運算符。
*pf(int)表示pf()是一個返回指針的函數(shù)。
(*pf)(int)表示pf是指向函數(shù)的指針。
在您正確聲明pf后,您可以為其賦值匹配函數(shù)的地址:
double my_func(int); double (*pf)(int); pf = my_func; // pf now points to the my_func() function
my_func()必須匹配簽名和返回類型的pf。
(*pf)起到與函數(shù)名稱相同的作用。
我們可以使用(*pf),就像它是一個函數(shù)名一樣:
double (int); double (*pf)(int); pf = my_func; // pf now points to the my_func() function double x = my_func(4); // call my_func() using the function name double y = (*pf)(5); // call my_func() using the pointer pf
以下代碼演示了在程序中使用函數(shù)指針。
#include <iostream>
using namespace std;
double my_func(int);
void estimate(int lines, double (*pf)(int));
int main(){
int code = 40;
estimate(code, my_func);
return 0;
}
double my_func(int lns)
{
return 0.05 * lns;
}
void estimate(int lines, double (*pf)(int))
{
cout << lines << " lines will take ";
cout << (*pf)(lines) << " hour(s)\n";
}
上面的代碼生成以下結(jié)果。
更多建議: