函数指针

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

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

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能让我们简化使用了函数指针的代码

 1 typedef bool(*FuncP)(const string&,const string &);

 2 typedef 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