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

这篇文章主要介绍了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?"<    cin>>code;
    cout<<"Here's Betsy's estimate:"<    estimate(code,betsy);
    cout<<"Here's Pam's estimate:"<    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<}

以上就是c++函数指针使用示例分享的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言