首页 > 其他 > 详细

指向函数的指针

时间:2015-07-31 16:20:34      阅读:247      评论:0      收藏:0      [点我收藏+]

bool(*pf)(const string &, const string &);

// int(&arr)[10]

//int  (*p)[10]

 

typedefbool (*cmpFcn)(const string &, const string &);

cmpFcnpf;

pf=某函数名;     //注意函数名前没有&

pf=&某函数名;      //两者等价!!

pf("hi", "bye");// equivalent call: pf1 implicitly dereferenced

(*pf)("hi","bye"); // equivalent call: pf1 explicitly dereferenced  //两者等价

ps:如果指向函数的指针没有初始化,或者具有 0 值,则该指针不能在函数调用中使用。只有当指针已经初始化,或被赋值为指向某个函数,方能安全地用来调用函数。

 

pps:函数的形参可以是指向函数的指针!!

function

voiduseBigger(const string &, const string &, bool(conststring &, const string &));

void useBigger(const string &,const string &,bool (*)(const string &, conststring &));   //等价


pps:返回值可以是指向函数的指针

int(*ff(int))(int*, int);

阅读函数指针声明的最佳方法是从声明的名字开始由里而外理解。

ff(int)表示将 ff 声明为一个函数,它带有一个 int 型的形参。该函数返回int (*)(int*, int);

 

使用 typedef 可使该定义更简明易懂:

typedef int (*PF)(int*, int);

PF ff(int); // ff returns a pointer to function

或者

typedef int PF(int*, int);

PF* ff(int); // ff returns a pointer to function

 

几个例子:

// funcis a function type, not a pointer to function!

typedefint func(int*, int);

voidf1(func); // ok: f1 has a parameter of function type 等价于void f1( int(int*,int) );

funcf2(int); // error: f2 has a return type of function type

func*f3(int); // ok: f3 returns a pointer to function type

 

#include<iostream>

usingnamespace std;

 

intsum(int a, int b){

cout<<”hello world”<<endl;

}

intmain(int argc, char **argv) {

       int (*p[4])(int, int);        //函数指针的数组,也是从里向外看

       //p[0]=sum;

       p[0]=&sum;    //equivalent

       p[0](1,2);

       //(*p[0])(1,2);     //equivalent

    //(*(p[0]))(1,2);     //[]优先级高于*

       return 0;

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

指向函数的指针

原文:http://blog.csdn.net/qhairen/article/details/47170475

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!