C++学习笔记--函数指针

(1)C++指针函数基础

文章来自 C++ Primer Plus 第7章 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";
}

输出如下:

wang@wang:~/c++$ ./a.out
How many lines of code do you need? 2
Here's Betsy's estimate:
2 lines will take 0.1 hour(s)
Here's Pam's estimate:
2 lines will take 0.0616 hour(s)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值