什么是函数指针
bool lengthCompare(const string &, const string &); // 函数指针pf,指向一个返回值为bool类型,参数为两个string引用的函数 bool (*pf)(const string &, const string &); // 这是一个函数指针 // 函数pf, 返回值为bool类型,参数为两个string引用 bool *pf(const string&, const string&); // 这是一个函数 // 在函数指针的声明中,括号是必不可少的部分。
如何使用函数指针
直接将函数指针当作函数名称来使用
pf = lengthCompare; pf = &lengthCompare; // 以下三个书写方式都是等价的 bool b1 = pf("hello", "goodbye"); bool b2 = (*pf)("hello", "goodbye"); bool b3 = lengthCompare("hello", "goodbye");
重载函数的指针
重载函数的指针必须与某一个重载的参数列表精确匹配,在这种情况下就与一般的函数指针没有什么区别了
而使用函数指针的调用并不能触发重载的特性。
函数指针形参
我们可以将函数指针当作一个参数传递进函数中
// 在参数列表中,函数会被自动转换为一个函数指针 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&) ); useBigger(s1, s2, lengthCompare);
返回指向函数的函数指针
我们也可以将函数指针当做一个返回值
// 下面的表达式,申明了一个返回函数指针的函数 // f1(int) 是函数的调用部分 // int (*)(int *, int) 表明,返回一个int返回值,参数为两个int的函数指针 int (*f1(int))(int *, int); // 我们可以使用一下的简化形式来书写,便于理解 // 1. typedef或using // 使用FUN来表示这个函数指针 typedef int (*Fun)(int *, int); using F = int (*)(int *, int); // F为函数指针类型 using FF = int (int *, int); // FF为函数类型 // 2. 使用auto和decltype string::size_type sumLength(const string&, const string&); string::size_type largerLength(const sring&, const string&); decltype(sumLength) * getFcn(const string &); // decltype作用于函数时,返回的是函数类型而不是指针,需要加*表示指针