函数指针指向某种特定类型。 函数的类型由它的返回类型和形参类型共同决定, 与函数名无关。
要想声明一个可以指向该函数的指针, 只需要用指针替换函数名即可:
eg: bool LengthCompare(const string &, const string &);
bool (*pFn) (const string &, const string &);
注:*pFn 的()是必须的,如果不加,pFn则成为返回值为bool*的函数
当把函数名作为一个值使用时,该函数自动转换成指针。
eg: pFn = LengthCompare; // 此时pFn指向LengthCompare函数,直接调用pFn就相当于调用LengthCompare函数
注:函数赋值没有转换,只有返回值和形参都相同的才可以赋值
使用类型别名简化使用:
// Func和Func2都是函数类型
typedef bool Func(const string &, const string &);
typedef decltype(LengthCompare) Func2;
// pFunc和pFunc2都是指向函数的指针类型
typedef bool (*pFunc)(const string &, const string &);
typedef decltype(LengthCompare) *pFunc2;
函数指针形参:
当函数作为参数时,无论是函数类型还是函数指针类型,都会被当做指针类型。
// 这两种声明是等价的
void UseBigger(const string &, const string &, Func);
void UseBigger(const string &, const string &, pFunc);
返回指向函数的指针:
using Fun = int(int *, int); // Fun是函数类型
using pFun = int(*)(int*, int); // pFun是指针类型
pFun f1(int);
F* f1(int); // 前两个都是返回函数指针的函数,使用正确
F f1(int); // 使用错误:返回类型不能自动转化成指针
直接定义: int(*f1(int)) (int*, int); // 从内向外读
参考:
王刚; 杨巨峰. C++ Primer中文版:第5版
原文:https://www.cnblogs.com/-life-long-learning/p/14414925.html