概念:函数指针是指指向函数而非指向对象的指针。
函数指针指向一个函数类型,函数类型由其返回类型以及形参表确定,与函数名无关:
bool (*pf) (const string&, const string&);
pf points to function returning bool that takes two const string references.
1 用typedef简化函数指针的定义
eg: typedef bool (*cmpFcn) (const string& ,const string&);
该定义表示cmpFcn是一种指向函数的指针类型的名字。该指针类型为“指向返回bool类型并带有两个const string引用形参的函数的指针”。以后使用这种函数指针类型时,只需直接使用cmpFcn即可。
2 指向函数的指针的初始化和赋值
在引用函数名但又没调用该函数时,函数名将被自动解释为指向函数的指针。假设有函数:
// compares lenghts of two strings bool lengthCompare(const string& ,const string&);
除了用作函数调用的左操作数以外,对lengthCompare的任何使用都被解释为如下类型的指针: bool (*) (const string& , const string&);
可以使用函数名对函数指针做初始化或赋值:
cmpFcn pf1 = 0;
cmpFcn pf2 = lengthCompare;
pf1 = lengthCompare;
pf2 = pf1;
此时,直接引用函数名等效于在函数名上应用取地址操作符:
cmpFcn pf1 = lengthCompare;
cmpFcn pf2 = &lengthCompare;
将函数指针初始化为0,表示该指针不指向任何函数。
3 通过指针调用函数
cmpFcn pf = lengthCompare;
lengthCompare("hi","bye");
pf("hi","bye");
(*pf) ("hi","bye");
4 函数指针形参
函数的形参可以是指向函数的指针。这种形参可以用以下两种形式编写:
// third parameter is a function type and is automatically treated as a pointer to function 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&, boo (*) (const string&,const string& ));
5 返回指向函数的指针 函数可以返回指向函数的指针,但是挺绕的:
int ( *ff(int) ) (int* , int);
ff(int) 将ff声明为一个函数,它带有一个int形参。该函数返回
int (*) (int* ,int);
它是一个指向函数的指针,所指向的函数返回int型并带有两个分别是int*型和int型的形参。
使用typedef可使该定义更简单易懂:
// PF is a pointer to a function returning an int , taking an int* and an int
typedef int (*PF) (int*,int);
PF ff(int);
允许将形参定义为函数类型,但函数的返回类型则必须是指向函数的指针,而不能是函数。
typedef int func(int*, int);
void f1(func); // ok : f1 has a parameter of function type
func f2(int); // error : f2 has a return type of function type
func *f3(int); // ok : f3 returns a pointer to function type
|