这一段在公司的某个框架代码中看到了函数指针的使用。风格比较偏纯C,其实C++有更加合适的解决方案,在这里总结一下。
首先从函数指针说起。
一、函数指针
从定义上讲,函数指针指向的是函数而非对象,函数指针指向某种特定类型。其类型由函数的返回类型和形参类型决定。
声明方式如下:
bool (*pf)(const string &,const string &);
注意pf两侧的括号不能少,不然就变成了单纯的返回值为指针类型的函数声明。
使用方式如下:
bool lengthCompare(const string &a,const string &b){
return a.size()<b.size();
}
//same as pf = &lengthCompare
pf = lengthCompare;
bool b1= pf("hello","fun");
cout<<b1<<endl;
//这两个是等价的调用
bool b2 = (*pf)("hello","goodBye");
cout<<b2<<endl;
当然,函数指针也可以作为形参使用,用法如下:
void big(const string &a,const string &b,
bool (*pf)(const string &,const string &)){
//same as bool pf(const string &,const string &)
cout<<pf(a,b)<<endl;
}
如果嫌弃参数的表达式过于冗长,可以使用typedef定义类型。
typedef bool func(const string &,const string &);
typedef bool (*funcP) (const string &,const string &);
因为在作为参数传递的时候,函数类型会被自动转换为指针,因此有以下两种用法。
void small(const string &a,const string &b,funcP fp){
bool res=fp(a,b);
cout<<!res<<endl;
}
void smallTwo(const string &a,const string &b,func fp){