指向函数的指针

函数指针是指向函数(而不是一般的数组,变量)的指针,这个特定的函数由其返回值和形参表决定,与函数名无关:

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值