c++之指针二

函数指针:

与数据项类似,函数也有地址。函数的地址是存储其机器语言代码的内存开始地址。

(1)获取函数指针:

获取函数地址很简单:只有使用函数名即可。也就是说think()是一个函数。则thinkj就是函数的地址。要将函数作为参数传递,必须传递函数名。一定要注意区分传递的是函数地址还是函数返回值。

(2)声明函数指针:

声明指向某种数据类型的函数指针时,必须指定指针指向的类型。同样,声明指向函数的指针时,也必须指定指针指向的函数类型。

(3)函数指针示例:

void estimate(int lines, double(*pf)(int));//计算函数运行时间,第二个参数传递的是函数指针
int main()
{
    int code;
    cin >> code;
    estimate(code, besty);
    estimate(code, pam);
    system("pause");
}
double besty(int lns)
{
    return 0.2*lns;
}

double pam(int lns)
{
    return lns*0.1 + lns*lns*0.4;
}
void estimate(int lines, double(*pf)(int))
{
    cout << lines;
    cout << (*pf)(lines) << "hours" << endl;

}

(4)深入理解函数指针

主要介绍函数指针声明及初始化。

#include<iostream>
using namespace std;
const double *f1(const double ar[], int n);
const double *f2(const double[], int);
const double *f3(const double [], int);

int main()
{
    double av[3] = { 1112.3,1542.6,2227.9 };
    const double *(*p1)(const double *, int) = f1;//声明一个指针指向函数f1并初始化
    auto p2 = f2; //c++自动类型转换功能
    cout << (*p1)( av, 3 ) << " :" << *(*p1) (av, 3 ) << endl; 
    cout << (*p2)(av, 3) << " :" << *(*p2) (av, 3) << endl;
    const double *(*pa[3])(const double *, int) = {f1,f2,f3}; //声明一个指针数组指向函数f1并初始化
    auto pb = pa;
    for (int i = 0; i < 3; i++)
    {
        cout << pa[i](av, 3) << ":" << *pa[i](av, 3)<<endl;
    }


    system("pause");
}
const double *f1(const double ar[], int n)
{
    return ar;
}
const double *f2(const double ar[], int n)
{
    return ar+1;
}
const double * f3(const double ar[], int n)
{
    return ar+2;
}

012FFE2C :1112.3
012FFE34 :1542.6
012FFE2C:1112.3
012FFE34:1542.6
012FFE3C:2227.9

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值