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]=∑ //equivalent
p[0](1,2);
//(*p[0])(1,2); //equivalent
//(*(p[0]))(1,2); //[]优先级高于*
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/qhairen/article/details/47170475