函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关。
int (*pi)(const string &,const string &);
这个语句将pi申明为指向函数的指针,它所指向的函数带有两个const string& 类型的形参和int类型的返回值。
*pi两侧的园括号是必须的:
int *pi(const string&,const string&);
这个语句声明了一个名为pi的返回值为bool*的函数。
1.使用typedef简化函数指针的定义
函数指针类型相当的冗长。使用typedef定义可以简化。
typedef bool (*pFunc)(const string&,const string&);
该定义表示pFunc是一种指向函数的指针类型的名字。该指针类型为“指向返回bool类型并带有两个const string引用形参的函数的指针”。在要使用这种函数指针类型时,只需要直接使用cmpFcn即可,不必每次都把整个类型声明全部写出来。
2.函数指针的初始化和赋值
在引用函数名但又没有调用该函数时,函数名将会被自动解释为指向函数的指针。假设有函数:
bool lengthCompare(const string &,const string &);
除了作函数调用的左操作数以外,对lengthCompare的所有操作将会被解释为如下类型的指针:
bool (*)(const string&,const string&);
可以用函数名对函数指针做初始化或者赋值:
pFunc p1=0;
pFunc p2=lengthCompare;
此时直接使用函数名等于在函数名上做取地址操作。
lengthCompare等于&lengthCompare
3.通过指针调用函数
pFunc pf=lengthCompare;
pf("hi","bbbbb");
或者(*pf)("hi","dfadsad");
4.函数指针形参
函数的参数是指向函数的指针,可以使用下面的方式来声明
void getCount(int cc,bool(string&,string&));
void getCount(int cc,bool (*)(string&,string&));
void getCount(int cc,bool (*pf)(string&,string&));
写函数的时候应该如下写
void getCount(int cc,bool (*p)(string&,string&))
{
}
5.指向重载函数的指针
C++允许使用函数指针指向重载函数:
指针的类型必须与重载函数的一个版本精确匹配,如果没有精确匹配的函数,则对该指针的赋值将导致编译错误。
extern void ff(vector<double>)
extern void ff(unsigned int)
void (*pf)(unsigned int)=&ff; //ok,第二个
void (*pf1)(int) =&ff; //error,没有精确匹配
double (*pf2)(vector<double>)=&ff; //error,返回类型不匹配