函数指针

---恢复内容开始---

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

bool LengthCompare(const string &,const string &)

该函数的类型是bool(const string& ,const string&)。想要声明一个指向改函数的指针,只需要用指针特换函数名即可:

bool (*pf)(const string&, const string&);//未初始化

赋值我们可以通过两种方法赋值:

pf=LengthCompare;

pf=&LengthCompare;

我们还可以直接使用指向函数的指针调用函数,无须提前解引用:

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

指向不同函数类型的指针之间不存在转换。

重载函数指针

使用重载函数时,上下文必须清晰地定界到底选用了哪个函数,如果定义了指向重载函数的指针.

函数指针形参

虽然不能定义函数类型的形参,但是形参可以是指向函数的指针。此时,形参看起来是函数类型,实际上确实当成指针使用:

1 //第三个形参是函数类型,它会自动地转成指向函数类型的指针
2 void useBigger(const string &s1,const string &s2,bool pf(const string &,const string&));
3 //等价
4 void useBigger(const string &s1,const string &s2,bool (*pf)(const string&,const string&));
5 
6 useBigger(s1,s2,lengthCompare);

正如uesBigger函数的声明所示,直接使用函数指针类型显得冗长而复杂,类型别名和decltype能让我们简化使用了函数指针的代码

1typedefbool(*FuncP)(conststring&,conststring&);

2typedef decltype(lengthCompare) *FuncP2;

1 void useBigger(const string &,const string&,Func);
2 void useBigger(const string &,const string&,FuncP2);

返回指向函数的指针

using F=int(int*,int)//F是函数类型
using PF=int*(int*,int)//F是指针类型

F f1*(int)  //显式的指定返回类型是指向函数的指针
PF f1(int)  //PF是指向函数的指针,f1返回指向函数的指针

//直接声明f1:
int (* f1(int) ) (int*,int)

//C++ 11新特性
auto f1(int)->int*(int*,int)

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

  1. ```
    如果我们明确知道返回的函数的哪一个就能使用该方法。

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

decltype(sunLength) *getFcn(const string&);
```

当我们将decltype作用于某个函数是,它返回函数类型而非指针类型。

原文链接: https://www.cnblogs.com/huangzhenxiong/p/7772627.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/262503

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午3:12
下一篇 2023年2月14日 下午3:13

相关推荐