函数指针
函数指针指向函数而非普通变量。和其他指针一样,函数指针指向某种特定的类型。(函数的类型由它的***返回值***和***形参类型***共同决定,如:bool func(const string& x, const string& y),该函数的类型是bool(const string&, const string&)。 )
声明一个指向函数的指针
//原函数
bool lengthCompare(const string&, const string&);
//pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型
bool (*pf) (const string &, const string &);
注意:
- 指针pf未初始化,可以将pf初始化为空指针:pf = 0;
- pf两端的括号必不可少。如果省略,则:
//声明一个名为pf的函数,该函数返回bool
bool *pf(const string &, const string &);
使用函数指针
//pf指向名为lengthCompare的函数
pf = lengthCompare;
//使用指针调用该函数,由于函数名是指向该函数的指针,无需提前解引用
bool b1 = pf(“hello”, “goodbye”);
C++也同时支持使用取地址符合解引用操作符的版本,这种看起来更像是指针操作:
//将lengthCompare函数的地址赋给pf
pf = &lengthCompare;
//使用指针调用该函数
bool b2 = (*pf) (“hello”, “goodbye”);
注意: 向函数指针赋值时,函数类型与指针类型需精确匹配。如:bool cstringCompare(const char*, const char*); 我们不能将cstringCompare赋给pf。
使用类型别名进行简化
//Func是函数类型
typedef bool Func(const string&, const string&);
typedef decltype(lengthCompare) Func;
//FuncP是指向函数的指针
typedef bool (*FuncP) (const string&, const string&);
typedef decltype(lengthCompare) * FuncP;
using F = int(int*, int); //F是函数类型
using PF = int (*) (int *, int); //PF是函数指针类型
使用typedef关键字或using声明进行简化,这在声明有函数指针类型参数的函数或返回指向函数的指针的函数时很有用。
如:
void useBigger(const string&,const string&, Func);
//等价声明 void useBigger(const string &,const string &, bool pf(const string &, const string &)); >注意:虽然第三个参数是函数类型,它会自动转换为指向函数的指针(我们不能传递函数类型的参数)
void useBigger(const string &, const string &, FuncP);
//等价声明void useBigger(const string &, const string &, bool (*pf) (const string &, const string &));
PF f1(int); //正确:返回指向函数的指针
F f1(int); //错误:F是函数类型,不能返回一个函数
F * f1(int); //正确:显示地指定返回类型是指向函数的指针
//等价声明:int (*f1(int)) (int *, int);
参考:
《C++ Primer》第5版