函数指针指向的是函数。和其他的指针一样,函数指针指向某种函数类型,函数的类型由函数的返回类型和形参类型决定,与函数名无关
例如:
//一个比较string长度大小的函数
bool stringLengthCompare(const string& left, const string& right);
//这个函数的类型是bool (const string& left, const string& right);
int main()
{
//一个指向这种类型的函数指针
bool (*pf)(const string& left, const string& right);//没有初始化可以初始化返回0或者nullptr
//*pf两边的括号不能少,少了就不是函数指针了
//而是一个返回bool*的函数了 bool *pf(const string& left, const string& right)
string left("1234");
string right("123456");
//函数指针的使用
pf = stringLengthCompare;//函数名就是函数的地址或者 pf = &stringLengthCompare;
bool res = stringLengthCompare(left, right);
res = pf(left, right);//res = (*pf)(left, right);
return 0;
}
bool stringLengthCompare(const string& left, const string& right)
{
return left.size() > right.size();
}
void ff(int);
void ff(double);
int main()
{
//编译器通过指针类型决定选取哪一个ff函数,使函数指针和ff函数精确匹配
void (*pf)(int) = ff;
void (*pf1)(double) = ff;
return 0;
}
bool stringLengthCompare(const string& left, const string& right)
{
return left.size() > right.size();
}
//第三个参数是函数类型,它会自动的转换成指向函数的指针
void useBigger(const string& s1, const string& s2, bool pf(const string&, const string&));
//第三个参数是函数指针,显式的将形式参数定义成指向函数的指针
void useBigger(const string& s1, const string& s2, bool (*pf)(const string&, const string&));
int main()
{
string s1("sfw");
string s2("1234");
useBigger(s1, s2, stringLengthCompare);
return 0;
}
//对于函数类型
typedef bool Func(const string&, const string&);
typedef decltype(stringLengthCompare) Func1;
//对于函数指针类型
typedef bool(*pFunc)(const string&, const string&);
typedef decltype(stringLengthCompare) *pFunc1;
//使用简化后的函数指针来重新声明useBigger
void useBigger(const string& s1, const string& s2, Func pf);
void useBigger(const string& s1, const string& s2, Func1 pf);
void useBigger(const string& s1, const string& s2, pFunc pf);
void useBigger(const string& s1, const string& s2, pFunc1 pf);
int main()
{
string s1("sfw");
string s2("1234");
useBigger(s1, s2, stringLengthCompare);
return 0;
}
函数虽然不能作为一个返回值,但是指向函数的指针却可以
//当函数指针作为返回值使用时
int sumLength(int*, int);
using F = int(int*, int); //F是一个函数类型
using PF = int(*)(int*, int); //PF是一个函数指针类型
PF f1(int);
F* f2(int);
F f3(int);//这个声明是错误的,不能返回一个函数
//当然也可以这样子声明一个f1,很繁琐
int (*f1(int))(int*, int);
//C++11中可以使用auto和decltype来简化上面的声明
//使用auto
auto f1(int) -> int(*)(int*, int);//尾置声明
//使用decltype,使用decltype的时候,返回的是一个函数类型,而不是函数指针,需要显式的加上*
decltype(sumLength) * getFunc(int);
函数指针当然也可以作为谓词传递到泛型算法中,这个后面再写