初识C++ - 函数指针

函数指针指向的是函数而非对象。和其他的指针一样,函数指针指向某种特定类型。函数的类型有返回类型和形参类型共同决定,与函数名无关。比如:

bool lengthCompare(const string &s1, const string &s2);
//pf指向一个函数,该函数的形参有两个const string引用,返回值为bool
bool (*pf)(const string &, const string &);

从声明的名字开始观察,pf前面有个*,因此pf是个指针;右侧是形参列表,表示pf指向的是函数;左侧表示返回类型是bool。

使用函数指针

当把函数名作为一个值使用时,该函数会自动转换成指针。此外,还可以直接使用函数指针调用函数,不用提前解引用指针(加上*)

//把lengthCompare的地址给pf
pf = (&)lengthCompare // 取地址符号可选

//b1 = b2 = b3 三个等价调用
bool b1 = pf("hello", "bye");
bool b2 = (*pf)("hello", "bye");
bool b3 = lengthCompare("hello", "bye"); 

在指向不同函数类型的指针之间不存在转换规则,但可以给指针赋值一个nullptr 或者 0的常量表达式,表示该指针没有指向任何一个函数。

重载函数指针

当使用重载函数时,上下文必须清晰,有一个确定精确匹配的函数。eg:

void ff(int *)
void ff(unsigned int);

void (*pf1)(unsigned int) = ff //指向第二个
void (*pf2)(int) = ff //无匹配的函数
double (*pf3)(int *) = ff //返回类型不匹配

函数指针形参

和数组类似,虽然不能定义函数类型的形参,但可以是函数指针。

//函数类型将自动转换为指针类型
void useBigger(const string &s1, const string &s2, bool pf(const string &, const string &));
=
void useBigger(const string &s1, const string &s2, bool (*pf)(const string &, const string &));
//调用
userBigger(s1, s2, lengthCompare);

上面定义代码略显臃肿,可以使用typedef 和 decltype 简化代码。

//函数类型
typedef bool func(const string&, const string&);
typedef decltype(lengthCompare) func2;
//函数指针
typedef bool (*funcp)(const string&, const string&);
typedef decltype(lengthCompare) funcp2;

//调用, 编译器自动将func转换为指针
void uerBigger(const string &s1, const string &s2, func)
void uerBigger(const string &s1, const string &s2, funcp2)

返回函数指针

和数组类似,无法返回一个函数,但可以返回函数指针。与调用不同,编译器不会自动把函数类型转换为函数指针,必须我们自己把类型写成指针类型。最简单的方式就是使用类型别名:

using f = int(int*, int);//f是函数类型
using pf = int(*)(int *, int);//pf是指针类型

//等价声明
pf f1(int);
f f1(int); //错误 返回类型必须为指针类型
f *f1(int);
int (*f1(int))(int*, int);
auto f1(int) -> int(*)(int*, int);

使用auto和decltype

在使用 decltype时,我们必须知道他的返回类型时函数而非指针,我们必须加上*表示返回的是指针。

string:: size_type sumLength(const string&, const string&);
string:: size_type largerLength(const string&, const string&);
decltype(sumLength) *getFcn(const string &);

参考:C++Primer第五版

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值