c++之指针二

来源:互联网 发布:淘宝怎么设置快递费 编辑:程序博客网 时间:2024/05/20 01:13

函数指针:

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

(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 0
原创粉丝点击