函数指针的类型只与其返回类型及形参类型共同决定,和函数名无关
bool (*p)(const string&,const string&);//p是一个指向返回值为布尔类型形参为string类型常量引用
//的函数的指针
//注意*p两端的圆括号不可省略
当我们把函数名当作一个值使用时,它会自动转换程一个指针
bool lengthCompare(const string&,const string&);
p=lengthCompare;//p指向该函数
p=&lengthCompare;//等价赋值
我们可以直接通过函数指针调用函数,无需提前解引用
bool b1=p("hellow","byebye");
bool b2=*p("hellow","byebye");
bool b3=lengthCompare("hellow","byebye");
在指向不同函数类型的指针之间不存在转换规则
重载函数的指针
如果定义了指向重载函数的指针,编译器通过指针的类型选择函数,指针类型必须与重载函数中的某一个精确匹配
void f1(int *);
void f1(unsigned int);
void (*p)(unsigned int)=f1;//p指向f1(unsigned int)
void (*p2)(int)=f1;//错误,无匹配项
double(*p3)(unsigned int)=f1;//错误,返回值不同
函数指针形参
将函数放在形参列表中时,看起来是函数其实被当成指针使用
void useBugger(const string&,const string&,bool p(const string&,const string&));
//等价声明
void useBugger(const string&,const string&,bool(*p)(const string&,const string&));
在调用时,可以直接将函数作为实参使用,它会被自动转换成指针
useBugger(s1,s2,lengthCompare);
在将函数指针作为形参时,显得繁杂,我们可以用typedef和decltype关键字简化这个过程
typedef bool func(const string&,const string&);
typedef decltype(lengthCompare) func2;//等价声明
//func和func2是函数类型
typedef bool (*funcp)(const strng&,const string&);
typedef decltype(lengthCompare) *funcp2;//注意加*字符
在用关键字简化之后的函数和函数指针重新声明useBugger函数明显简单很多
void useBugger(const string&,const string&,func);//func是函数类型,它会被自动转换成指针类型
void useBugger(const string&,const string&,funcp);
返回指向函数的指针
如果我们想让函数返回指向函数的指针,我们必须将返回类型写为指针类型,编译器不会自动将函数返回类型转换为指针类型。最简单的方法是通过类型别名。
using F=int(int*,int);//F是函数类型
using Fp=int(*)(int*,int);//Fp是指针类型
Fp f1(int);//true
F f1(int);//错误,F是函数类型,函数不可以返回函数类型
F *f1(int);//正确
//当然,我们也可以直接声明f1而不使用类型别名
int (*f1(int))(int*,int);//由内而外去理解
//我们也可以通过尾置返回类型声明
auto f1(int)->int(*)(int*,int);
如果我们非常清晰的指导返回的函数指针类型,我们可以直接用decltype关键字来简化声明
string::type sumLength(const string&,const string&);
string::type LargerLength(const string&,const string&);
decltype(sumLength) *getFc(const string&);//*必须加