
c++关于函数指针的问题
doublebetsy(intlines){return0.05*lines;}doublepam(intlines){return0.03*lines+0.004*li...
double betsy(int lines){return 0.05*lines;}
double pam(int lines){return 0.03*lines+0.004*lines*lines;}
void estimate(int lines,double (*pf)(int))
{
using namespace std;
cout<<lines<<" lines will take "<<(*pf)(lines)<<"hour(s)"<<endl;
}
int main()
{
int code;
cout<<"How many lines of code do you need?"<<endl;
cin>>code;
cout<<"Here's Betsy's estimate:"<<endl;
estimate(code,betsy);
cout<<"Here's Pam's estimate:"<<endl;
estimate(code,pam);
getchar();
getchar();
return 0;
}
前三个是要调用的函数,问题是在主函数中estimate(code,betsy);这句语句是什么意思?betsy不是一个函数么?为什么不用给betsy参数,而且直接是把code作为参数调给了betsy 展开
double pam(int lines){return 0.03*lines+0.004*lines*lines;}
void estimate(int lines,double (*pf)(int))
{
using namespace std;
cout<<lines<<" lines will take "<<(*pf)(lines)<<"hour(s)"<<endl;
}
int main()
{
int code;
cout<<"How many lines of code do you need?"<<endl;
cin>>code;
cout<<"Here's Betsy's estimate:"<<endl;
estimate(code,betsy);
cout<<"Here's Pam's estimate:"<<endl;
estimate(code,pam);
getchar();
getchar();
return 0;
}
前三个是要调用的函数,问题是在主函数中estimate(code,betsy);这句语句是什么意思?betsy不是一个函数么?为什么不用给betsy参数,而且直接是把code作为参数调给了betsy 展开
2个回答
展开全部
double (*pf)(int)是申请一个存放函数地址的变量pf,作用是存放函数地址。*pf是函数指针。
estimate(code,betsy);这里可以写成estimate(code,&betsy);感觉更方便理解,&betsy放入函数的地址,使得(*pf)(lines)等价于betsy(lines)。
如果想想调用pam(lines),在主函数中写成estimate(code,pam);//此处也可以写成estimate(code,&betsy);效果运行结果相同。
estimate(code,betsy);这里可以写成estimate(code,&betsy);感觉更方便理解,&betsy放入函数的地址,使得(*pf)(lines)等价于betsy(lines)。
如果想想调用pam(lines),在主函数中写成estimate(code,pam);//此处也可以写成estimate(code,&betsy);效果运行结果相同。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询