C++随笔(三)函数指针

函数指针的作用

允许在不同的时间传递不同的函数地址,这意味着可以在不同的时间使用不同的函数

1.获取函数地址

只使用函数名(后面不跟参数)
例子对于函数 think();

  • think: 函数地址
  • think():函数返回值

2.声明函数指针

基本函数声明: double pam(int);
函数指针声明:double (*pf)(int);

3.使用指针来调用函数

double pam(int);
double (*pf)(int);

pf = pam;
double x = pam(4);
double y = (*pf)(5)

//同样也可以像调用不同函数的方式调用函数指针
double y = pf(5);

4.实例

#include<iostream>

double betsy(int);
double pam(int);

void estimate(int lines, double (*pf)(int));

int main(int argc, char const *argv[])
{
    using namespace std;
    int code;
    cout << "How many lines of code do you need? ";
    cin >> code;
    cout << " Here is Betsy's estimaye:\n";
    estimate(code, betsy);
    cout << " Here is  pam's estimaye:\n";
    estimate(code, pam);
    return 0;
}

double betsy(int lns)
{
    return 0.05 * lns;
}
double pam(int lns)
{
    return 0.03 * lns + 0.0005 * lns * lns;
}

void estimate(int lines, double (*pf)(int))
{
    using namespace std;
    cout << lines << " linrs will take ";
    cout << (*pf)(lines) << " hour(s)\n";
}

输出

How many lines of code do you need? 50
 Here is Betsy's estimaye:
50 linrs will take 2.5 hour(s)
 Here is  pam's estimaye:
50 linrs will take 2.75 hour(s)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值