C++ 函数指针

函数指针

1)函数指针指的是函数而非对象。

2)要想声明一个指向函数的指针,只要用指针替换函数名即可:

bool lengthcompare(const string&,const string&);

bool (*pf)(const string&,const string&);(此处声明了一个函数指针)

下面为函数指针赋值:有以下两种等价方法

pf=lengthcompare;

pf=&lengthcompare

下面是三个等价调用

bool b1=pf(“hello”,”goodbay”);

bool b2=(*pf)(“hello”,”goodbay”);

bool b3=lengthcompare(“hello”,”goodbay”);

3)在指向不同函数类型(返回类型,形参类型)的指针之间不存在转换规则

4)函数指针与形参

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

void usebiggerconst string &s1const string &s2

bool pf(const string &,const string&));

void usebiggerconst string &s1const string &s2

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

void usebiggerconst string &s1const string &s2

lengthcompare);

(5)返回指向函数的指针

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

例如,下面是个返回类型:

int (*f1(int)) (int *, int );//声明一个返回函数指针的函数

f1有形参说明f1是函数;f1前有*说明f1返回一个指针;进一步发现指针的类型本身也有形参列表,因此指针指向了函数,该函数返回类型是int,形参是(int*,int)。

f1函数返回一个类型是intint*int)的指针。

尾置返回类型:auto f1(int)->int (*)(int* ,int) ;

 

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值