本次是讲解的函数指针的运用,不过我之前还没用过,在这跟大家分享下。
通常,要声明指向特定类型的函数的指针,可以首先编写这种函数的原型然后用(*pf)替换函数名,这样pf就是这类函数的指针。
例如 double pam(int );
double (*pf)(int);在这就是讲pam替换为了(*pf),而pf就是这类函数的指针。
2.获取函数的地址
获取函数地址很简单,只要使用函数名(后面不跟参数)就可以。如果跟参数的话,就是将其返回值传递了。
实例代码如下:
#include "stdafx.h"
#include<iostream>
using namespace std;
double betsy(int);
double pam(int);
void estimate(int lines,double (*pf)(int));
int _tmain(int argc, _TCHAR* argv[])
{
int code;
cout<<"How many lines of code do you need ?";
cin>>code;
cout<<"Here's Betsy's estimate:"<<endl;
estimate(code,betsy);
cout<<"Here's Pam's estimate:"<<endl;
estimate(code,pam);
system("pause");
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))
{
cout<<lines<<"lines will take ";
cout<<(*pf)(lines)<<" hour(s)"<<endl;
}