学习C++——函数指针

函数指针指向的是函数而不是对象。

bool length(const string &, const string &);
如果要声明一个指向该函数的指针,只需要将指针替换函数名。

bool (*pf)(const string &, const string &);
如果没有*f两边():

bool *pf(const string &, const string &);
声明了一个名为pf的函数,该函数返回类型为 bool *

1、使用函数指针

<pre name="code" class="cpp">pf = length;
pf = &length;//两条语句是等价的,pf指向函数名为length的函数。
bool (*pf)(const string &,const string &) = length;
 
 

<span style="font-size:10px;font-weight: normal;">bool b1 = pf("hello","word");
bool b2 = (*pf)("hello","word");
bool b3 = length("hello","word");//三条语句是等价的</span>

2、重载函数的指针

当使用重载函数时,必须清晰地界定到底应该选用哪个函数。如果定义了指向重载函数的指针,编译器通过指针类型决定选用哪个函数,指针类型必须与重载函数中的某一个精确匹配。

3、函数指针形参

和数组类似,不能定义函数类型的形参,但是形参可以是指向函数的指针。
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 &));//两种声明是等价的。这个是显式地将形参定义成指向函数的指针
useBigger(s1, s2, length);//会自动地将函数length转换成指向该函数的指针

decltype
decltype( (变量名) ) 的返回结果永远都是引用。
decltype(  变量名  ) 的返回结果只有当变量本身是一个引用时才是引用。

4、返回指向函数的指针

虽然不能返回一个函数,但是可以返回指向函数类型的指针。
我们必须把返回类型写成指针形式,编译器不会自动地将函数返回类型当成对应的指针类型处理。

using F = int(int *, int);
using PF = int (*)(int *, int);
PF f1(int);//正确
F f1(int);//错误
F *f1(int);//正确

5、将auto和decltype用于函数指针类型

string::size_type sumLength(const string &, const string &);
string::size_type largerLength(const string &, const string &);

decltype(sumLength) *getFcn(const string &);//getFcn返回类型是 指向sumLength函数的指针
//decltype作用于某个函数时,返回函数类型不是指针类型,所以要加上*来表明需要返回指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值