假设要设计一个函数,并且希望不同程序员都将使用该函数。对于所有用户来说,函数中的一部分代码都是相同的,但该函数允许每个程序员提供自己的算法来估算时间。为此,将程序员要使用的算法函数的地址传递给该函数。
1.获取函数的地址
获取函数的地址:只要使用函数名(后面不跟参数)即可。要将函数作为参数进行传递,必须传递函数名。一定要区分传递的是函数的地址还是函数的返回值:
process(think);
process()调用使得process()函数能够在其内部调用think()函数;
thought(think());
thought()调用首先调用think()函数,然后将think()的返回值传递给thought()函数。
2.声明函数指针
声明指向某种数据类型的指针时,必须指定指针指向的类型。声明应指定函数的返回类型以及函数的特征标。
double (*pf)(int);
3.使用指针来调用函数
(*pf)扮演的角色与函数名相同,因此使用(*pf)时,只需将它看作函数名即可:
double pam(int);
double (*pf)(int);
pf=pam;
double x=pam(4);
double y=(*pf)(5);
double y=pf(5);//允许 与上相同
程序:
#include<iostream>
double betsy(int);
double pam(int);
void estimate(int lines, double(*pf)(int));
int main()
{
using namespace std;
int code;
cout << "How many lines of code do you need? ";
cin >> code;
cout << "Here's Betsy's estimate:\n";
estimate(code, betsy);
cout << "Here's Pam's estimate:\n";
estimate(code, pam);
return 0;
}
double betsy(int lns)
{
return 0.05*lns;
}
double pam(int lns)
{
return 0.03*lns + 0.0004*lns*lns;
}
void estimate(int lines,double(*pf)(int))
{
using namespace std;
cout << lines << " lines will take ";
cout << (*pf)(lines) << "hours(s)\n";
}
函数特征标看似不同,但实际上相同:
const double * f1(const double ar[],int n);
const double * f2(const double [],int );
const double * f3(const double *,int );