函数指针与指针函数

假设要设计一个名为estimate()的函数,估算编写指定行数的代码所需的时间,并且希望不同的程序员都使用该函数。对于所有的用户来说,estimate()中一部分代码都是相同的,但该函数允许每个程序员都提供自己的算法来估算自己算法运行所需的时间。

为实现这种目标,采用的机制是,将程序员要使用的算法函数的地址传递给estimate()。因此,必须能完成下面工作:
(1)获取函数的地址;

(2)声明一个函数指针;

(3)使用函数指针来调用函数。

double pam(int);
double (*pf)(int);  //pf points to a function that return double
double *pf(int);    //pf() a function that returns a pointer-to-double

pam()的特征标和返回值类型必须与pf相同。

pf = pam;               //pf now points to the pam() function
double x = pam(4);      //call pam() using the function name
double y = (*pf)(5);    //call pam() using the pointer pf. 
double y = pf(5);       //also call pam() using the pointer pf
This means pf == (*pf).



猜你喜欢

转载自blog.csdn.net/WangJiankun_ls/article/details/78830940