函数指针

函数指针(指向函数的指针)CP221

//原函数
bool lengthCompare(const string &,const string &);
/*直接用指针替换函数名声明指向函数的指针
  如果不写括号则变成返回bool类型的指针*/
bool (*pf)(const string &,const string &)=lengthCompare;
/*调用方式*/
bool b1=lengthCompare("hi","hello");
bool b1=(*pf)("hi","hello");
bool b1=pf("hi","hello");//也可以直接使用指针调用
  • 指向不同函数类型的指针不存在转换规则
pf=nullptr;//不指向任何函数
int::size_type length(const string &,const string &);
pf=length;//错误,返回类型不匹配
bool lengthcompare(const char*,const char*);
pf=length;//错误,形参类型不匹配
void ff(int*);
void ff(unsigned int);
//函数指针的类型必须与某个重载函数精确匹配
void (*pf)(unsigned int)=ff;
  • 函数指针作为形参
bool lengthCompare(const string &,const string &);
//Func和Func2是函数类型
typedef bool Func(const string &,const string &);
typedef decltype(lengthCompare) Func2;
//在调用该函数的函数中,简化函数指针
void useBigger(const string &,const string &,Func);
//把函数直接当成实参使用时,编译器自动将其转化为指针
//Func和Func2是函数指针
typedef bool (*FuncP)(const string &,const string &);
//decltype的返回结果为函数类型,要加上*为函数指针
typedef decltype(lengthCompare) *FuncP2;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值