指向函数的指针
函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关:
// pf points to function returning bool that takes two const string references bool (*pf)(const string &, const string &);这个语句将 pf 声明为指向函数的指针,它所指向的函数带有两个 const string& 类型的形参和 bool 类型的返回值。
函数指针类型相当地冗长。使用 typedef 为指针类型定义同义词,可将函数指针的使用大大简化:
typedef bool (*cmpFcn)(const string &, const string &);该定义表示 cmpFcn 是一种指向函数的指针类型的名字。该指针类型为“指向返回 bool 类型并带有两个 const string 引用形参的函数的指针”。在要使用这种函数指针类型时,只需直接使用 cmpFcn 即可,不必每次都把整个类型声明全部写出来。
指向函数的指针的初始化和赋值
在引用函数名但又没有调用该函数时,函数名将被自动解释为指向函数的指针。假设有函数:// compares lengths of two strings bool lengthCompare(const string &, const string &);
除了用作函数调用的左操作数以外,对 lengthCompare 的任何使用都被解释为如下类型的指针:
bool (*)(const string &, const string &);
可使用函数名对函数指针做初始化或赋值:
cmpFcn pf1 = 0; // ok: unbound pointer to function cmpFcn pf2 = lengthCompare; // ok: pointer type matches function's type pf1 = lengthCompare; // ok: pointer type matches function's type pf2 = pf1; // ok: pointer types match此时,直接引用函数名等效于在函数名上应用取地址操作符:
cmpFcn pf1 = lengthCompare; cmpFcn pf2 = &lengthCompare;
通过指针调用函数
指向函数的指针可用于调用它所指向的函数。可以不需要使用解引用操作符,直接通过指针调用函数:
cmpFcn pf = lengthCompare; lengthCompare("hi", "bye"); // direct call pf("hi", "bye"); // equivalent call: pf1 implicitly dereferenced (*pf)("hi", "bye"); // equivalent call: pf1 explicitly dereferenced函数指针形参
/* useBigger function's third parameter is a pointer to function * that function returns a bool and takes two const string references * two ways to specify that parameter: */ // third parameter is a function type and is automatically treated as a pointer tofunction void useBigger(const string &, const string &, bool(const string &, const string &)); // equivalent declaration: explicitly define the parameter as a pointer to function void useBigger(const string &, const string &, bool (*)(const string &, const string &));
返回指向函数的指针