为什么只有函数指针而不是函数变量?

Leo*_*eon 5 c++ typedef function-pointers function

在C/C++中,我们可以声明/定义一个类型的函数指针,然后声明/定义这个类型的一些变量。但我认为这是模棱两可的。

例如:

typedef void ( *pFunc )();
// typedef void ( aFunc )();
void theFunc() {
   cout << "theFunc has been called successfully." << endl;
};

int main() {
   pFunc pf0 = theFunc;
   pFunc pf1 = &theFunc;

   pf0();
   ( *pf0 )();
   pf1();
   ( *pf1 )();
};
Run Code Online (Sandbox Code Playgroud)

理论上,只有pFunc pf1 = &theFunc;(*pf1)();是合法的,但以上都可以通过编译。

Pascal语法中,我们需要分别定义函数的vars或函数指针的vars,它们的含义是不同的,而且更加清晰(至少我是这么认为的)!

此外,我们不能声明/定义函数的变量而不是函数指针的变量!我尝试了以下并失败了。

typedef void ( aFunc )();
aFunc af0 = theFunc;
Run Code Online (Sandbox Code Playgroud)

如果使用其他类型,例如 int/double,则有非常严格的语法限制我们正确使用它们。(如果int*与 不同int,为什么*pf0与 相同pf0?!)

那么,我可以认为这是 C/C++ 标准的错误吗?

Leo*_*eon 0

我想我已经找到了答案。

事实上,C++ 标准提供了一种无需指针即可声明函数类型的方法。

例子:

#include <functional>

using AFunc_t = function<void( int )>;

void theFunc( int );

AFunc_t afunc = theFunc;
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助某人。