函数指针指向的是函数而非对象
bool lengthCompare (const string &,const string &);
要想声明一个指向函数的指针,只需要用指针替换函数名即可
//pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型
bool (*pf) (const string &,const string &);//只是声明,未初始化
声明了一个指向函数的指针,其中该函数的参数是两个const string 的引用,返回值是bool类型。
使用时需要赋值
pf =lengthCompare;//pf指向名为lengthCompare的函数
pf=&lengthCompare;//等价的赋值语句,取地址符&是可选的
使用时
bool b1=pf("hello","goodbye");
bool b2=(*pf)("hello","goodbye");
bool b3=LengthCompare("hello","goodbye");
//三个等价调用
当我们定义重载函数时,指针类型必须与重载函数中的一个精确匹配(形参列表,及返回值)
void ff(int *);
void ff(unsigned int);
void (*pf1) (unsigned int)=ff;//pf1指向ff(unsigned)
void (*pf2) (int) =ft;//错误,没有任何一个精确匹配
double (*pf3) (int *)=ff;//错误,没有任何一个匹配
函数指针形参
和数组类似,虽然不能定义函数类型的形参,但是形参可以是指向函数的指针
//第三个形参是函数类型,它会自动地转成指向函数类型的指针
void useBigger(const string &s1,const string &s2, bool pf(const string &,const string&));
//等价
void useBigger(const string &s1,const string &s2,bool (*pf)(const string&,const string&));
//自动将函数转换成指向该函数的指针
useBigger(s1,s2,lengthCompare);
但是上面这种做法并不建议,因为useBigger的声明语句显得繁琐,建议使用类型别名或decltype类型识别符来进行简化
//示例函数int func(int a,int b);
//指向函数的指针
using pFunc1=decltype(func)*;
typedef decltype(func)* pFunc2;
using pFunc3=int(*)(int a,int b);
typedef int(*pFunc4)(int a,int b);
//之后再用pFunc1......来当形参
会简便很多
因为decltype作用于函数时,返回的时函数类型而非指针类型,所以我们需要显式地加上*