函数指针是指向函数(而不是一般的数组,变量)的指针,这个特定的函数由其返回值和形参表决定,与函数名无关:
bool (*pf)(const string &, const string &);
这个语句将 pf 声明为指向函数的指针,它所指向的函数带有两个 const string& 类型的形参和 bool 类型的返回值。
函数指针的定义非常冗长,可以使用typedef来简化定义:
typedef bool (*cmpFcn)(const string &, const string &);
该定义表示 cmpFcn 是一种指向函数的指针类型的名字。该指针类型为“指向返回 bool 类型并带有两个 const string 引用形参的函数的指针”。在要使用这种函数指针类型时,只需直接使用 cmpFcn 即可,不必每次都把整个类型声明全部写出来。
在给指针初始化和赋值时,直接使用函数名即可(函数名等效为指向函数的指针),举个例子:
假设有函数:
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
注意,指向不同函数类型的指针之间不存在转换:
string::size_type sumLength(const string&, const string&);
bool cstringCompare(char*, char*);
// pointer to function returning bool taking two const string&
cmpFcn pf;
pf = sumLength; // error: return type differs
pf = cstringCompare; // error: parameter types differ
pf = lengthCompare; // ok: function and pointer types match exactly
有了指向函数的指针以后,我们就可以通过指针调用函数了:
cmpFcn pf = lengthCompare;
lengthCompare("hi", "bye"); // direct call
pf("hi", "bye"); // equivalent call: pf1 implicitly dereferenced
(*pf)("hi", "bye"); // equivalent call: pf1 explicitly dereferenced
当一个函数的返回值为指向函数的指针时,这个函数的定义就会变得很难理解:
int (*ff(int))(int*, int);
从里向外理解:
ff(int)表明一个参数为int类型的函数,这个函数返回int (*) (int*,int),这是一个指向函数的指针。这个指针指向的函数返回值为int型,参数为分为int*型和int型。
利用typedef可以是得定义更加简洁:
typedef int (*PF)(int*,int);
PF ff(int);