• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

c++函数指针使用示例分享

c++ 搞代码 4年前 (2022-01-06) 56次浏览 已收录 0个评论

这篇文章主要介绍了c++函数指针使用示例,需要的朋友可以参考下

需求
假设要设计一个名为estimate()的函数,估算编写指定行数的代码所需的时间,并且希望不同的程序员都可以使用该函数。

对于所有的用户来说,estimate()中一部分代码都是相同的,但该函数允许每个程序员提供自己的算法来估算时间。

为实现目标,采用的机制是,将程序员要使用的算法函数的地址传递给estimate()。

实现代码如下

代码如下:
// funpointer.cpp : 定义控制台应用程序的入口点。
//
#include “stdafx.h”
#include double betsy(int);
double pam(int);

//estimate函数的第二个参数接受一个函数指针
void estimate(int lines,double (*pf)(int));

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;
    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;
}
inline double betsy(int lines){return 0.05*lines;}

inline double pam(int lines){return 0.03*lines+0.004*lines*lines;}

inline void estimate(int lines,double (*pf)(int))
{
    using namespace std;
    cout<<lines<<" lines will take "<<(*pf)(lines)<<"hour(s)"<<来源gaodai#ma#com搞*!代#%^码网endl;
}

以上就是c++函数指针使用示例分享的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:c++函数指针使用示例分享

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址