函数指针指向的函数而不是对象。
函数指针指向某种特定的类型,函数的类型由它返回的类型和形参共同决定,与函数名无关。
声明函数指针,只需要使用指针替换函数名即可:
bool lengthCompare(const string&,const string&);
bool (*pf)(const string&,const string&); //定义一个指向上面函数的指针,括号不可少
使用函数指针
当把函数名作为一个值使用时,该函数自动转换成函数指针:
pf = lengthCompare;
pf = &lengthCompare; //等价的赋值语句,取地址符是可选的
使用函数指针调用函数:
bool b1 = pf("hello","world");
bool b2 = (*pf)("hello","world"); //解引用得到函数名
bool b3 = lengthCompare("hello","world");
函数指针和普通指针一样,可以赋值为nullptr
:
pf = nullptr; //表示不指向任何函数
函数指针形参
函数的形参可以是指向函数的指针。
void useBigger(const string &s1,const string &s2,bool lengthCompare(const string&,const string&));//形参看似是函数类型,但是实际上是函数指针
void useBigger(const string &s1,const string &s2,bool (*pf)(const string&,const string&));
直接使用函数指针可能看着冗长,可以使用类型别名。
返回指向函数的指针
函数可以返回指向函数类型的指针。
using F = int(int*,int); //F是函数类型
using pF = int(*)(int*,int); //pF是指针类型
需要注意的是,和函数类型的形参不同,返回类型不会自动的转换成指针,必须显示的将返回类型指定为指针。
pF f(int); //正确,pF是指向函数的指针,f返回指向函数的指针
F f(int); //错误,F是函数类型,f不能返回一个函数
F* f(int); //正确,显示地指定返回类型是指向函数的指针
直接声明:
int (*f(int))(int*,int);
尾置返回类型:
auto f(int)->int(*)(int*,int);
decltype用于指针类型
string::size_type sumLength(const string&,const string&);
decltype(sumLength) * getFunc(const string&);
需要注意的是,将 decltype
作用于一个函数时,它返回的是函数类型而不是指针类型,所以需要显示的指明指针类型。