函数指针

普通函数指针

函数指针声明

1
2
3
4
5
6
7
8
9
bool lengthCompare(const string&, const string&); 

bool (*pf)(const string& , const string&) = lengthCompare;

pf = lengthCompare;
pf = &lengthCompare;

bool b = pf("hello", "goodBye");
bool b = (*pf)("hello", "goodBye");

注意:

  • 此时的pf表示这是一个函数指针,而非函数指针类型,如果要表示指针类型需要使用指针别名(见下);
  • 当我们把函数名作为一个值使用时,该函数自动转换为指针;
  • 当我们使用函数指针调用该函数时,无需提前解引用指针;

使用指针别名

1
2
3
4
5
6
typedef bool(*Func)(const string&,const string&);
typedef decltype(lengthCompare) *Func;

using Func = bool(*)(const string&,const string&);
void useBigger(const string& s1, const string& s2, Func f); //将函数指针作为形参
Func f(int); //将函数指针作为返回值
  • decltype自动类型推导函数后还是函数,一定要加*
  • 使用using定义别名时要注意和typedef存在的区别
  • 尽量定义函数指针别名后再使用函数指针形参及返回,否则会降低代码的可读性

类函数指针

参考代码

使用std::function 和std::bind

0%