函数指针(指向函数的指针)CP221
//原函数
bool lengthCompare(const string &,const string &);
/*直接用指针替换函数名声明指向函数的指针
如果不写括号则变成返回bool类型的指针*/
bool (*pf)(const string &,const string &)=lengthCompare;
/*调用方式*/
bool b1=lengthCompare("hi","hello");
bool b1=(*pf)("hi","hello");
bool b1=pf("hi","hello");//也可以直接使用指针调用
- 指向不同函数类型的指针不存在转换规则
pf=nullptr;//不指向任何函数
int::size_type length(const string &,const string &);
pf=length;//错误,返回类型不匹配
bool lengthcompare(const char*,const char*);
pf=length;//错误,形参类型不匹配
void ff(int*);
void ff(unsigned int);
//函数指针的类型必须与某个重载函数精确匹配
void (*pf)(unsigned int)=ff;
- 函数指针作为形参
bool lengthCompare(const string &,const string &);
//Func和Func2是函数类型
typedef bool Func(const string &,const string &);
typedef decltype(lengthCompare) Func2;
//在调用该函数的函数中,简化函数指针
void useBigger(const string &,const string &,Func);
//把函数直接当成实参使用时,编译器自动将其转化为指针
//Func和Func2是函数指针
typedef bool (*FuncP)(const string &,const string &);
//decltype的返回结果为函数类型,要加上*为函数指针
typedef decltype(lengthCompare) *FuncP2;