//比较两个string的长度
bool lengthCompare(const string &, const string &);
//声明一个指向该函数的指针
bool (*pf)(const string &, const string &);
*pf 旁边的括号不能省略,如果不写这对括号那么pf是一个返回值为bool指针的函数。
使用函数指针
当我们把函数名当作一个值来使用时,该函数自动转换为指针,类似于使用内置数组时会自动转换为指针;
pf = lengthCompare;
pf = &lengthCompare; //等价的赋值语句
此外还可以直接使用指向函数的指针调用该函数,无需提前解引用指针,此操作同样类似于内置数组;
返回指向函数的指针
- 使用类型别名;
using f = int(int *, int); //f是函数类型
using pf = int(*)(int *, int); //pf是指针类型
- 直接声明;
int (*f1(int))(int *, int);
- 使用尾置返回类型的方式;
auto f1(int) -> int(*)(int *, int);