当前位置:嗨网首页>书籍在线阅读

29-函数指针示例

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

7.10.2 函数指针示例

程序清单7.18演示了如何使用函数指针。它两次调用estimate()函数,一次传递betsy()函数的地址,另一次则传递pam()函数的地址。在第一种情况下,estimate()使用betsy()计算所需的小时数;在第二种情况下,estimate()使用pam()进行计算。这种设计有助于今后的程序开发。当Ralph为估算时间而开发自己的算法时,将不需要重新编写estimate()。相反,他只需提供自己的ralph()函数,并确保该函数的特征标和返回类型正确即可。当然,重新编写estimate()也并不是一件非常困难的工作,但同样的原则也适用于更复杂的代码。另外,函数指针方式使得Ralph能够修改estimate()的行为,虽然他接触不到estimate()的源代码。

程序清单7.18 fun_ptr.cpp

// fun_ptr.cpp -- pointers to functions
#include <iostream>
double betsy(int);
double pam(int);
// second argument is pointer to a type double function that
// takes a type int argument
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) << " hour(s)\n";
}

下面是运行该程序的情况:

How many lines of code do you need? 30
Here's Betsy's estimate:
30 lines will take 1.5 hour(s)
Here's Pam's estimate:
30 lines will take 1.26 hour(s)

下面是再次运行该程序的情况:

How many lines of code do you need? 100
Here's Betsy's estimate:
100 lines will take 5 hour(s)
Here's Pam's estimate:
100 lines will take 7 hour(s)