Pointers to Function

Function type

A function type is determined by its return value and parameter list

Pointers to function

a pointer to funtion is a pointer points to a object of particular  function type

bool (*pf) (const string&, const string&);//definition

The parentheses is necessary

bool *pf(const string&, const string&);
//declares a function named pf that returns a bool*

using typedefs to simplify function pointer definition

	typedef bool (*cmp)(const string&,const string&);
	cmp pf1=0;//initialize a pointer with null

Initialization and Assignment

function name is implicit pointer of that function type

cmp pf1=lengthCompare;
//equivalent to cmp pf1=&lengthCompare
(why?)

There is no conversion between one pointer to function type and another


Application of function pointer

1 calling a function through a function pointer

bool lengthCompare(const string& s1,const string& s2){
	return s1.size()==s2.size()? true : false ;
}

	typedef bool (*cmp)(const string&,const string&);
	cmp pf1=lengthCompare;//initialize a pointer with null
	string s1="abc";
	string s2="abcsfd";
	bool flag;
	flag=lengthCompare(s1,s2);//method 1
	flag=pf1(s1,s2);//equivalent to *pf1(s1,s2)

2 passing a function as parameter to another

bool isSameLength(const string& s1,const string& s2, bool(*f)(const string& ,const string&)){
  if(f(s1,s2)) return true;
  else return false;
}

just a silly function

3 returning a pointer to function

example, a function returns a pointer to function type of int(int*,int)

int (*f(int))(int*,int);

for simplicity still typedef can be used

typedef int(*PF)(int*,int)
//syntax for typedef int(*)(int*,int) PF

PF f(int)

the return type of a function can only be pointer to function,but not function type itself(why?)
typedef int func(int,int)
//func is a function type,not a pointer to function

void f1(func);
//the parameter convert automatically to func*
func f2(int); //error
func *f3(int);//ok





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值