本地函数定义是非法的,这让我觉得很奇怪。就目前的情况而言,我怀疑它会很难实现,并且无缘无故地删除可能是潜在功能的功能(例如在 python 中)似乎很奇怪,尤其是对于像 C++ 这样的语言,您可以在其中如果你想的话,搬起石头砸自己的脚。如果允许这样的事情,局部函数定义的非法性似乎加倍奇怪。
int main()
{
void func(); // Allowed?
class BypassRules {
public:
static void func() { return; }
};
BypassRules::func();
func();
return 0;
}
void func() { return; }
奇怪的是,允许局部函数“声明”,但不允许定义。并且可以通过编写类封装器轻松绕过不允许局部函数定义的规则。那么,我可以澄清一下吗?为什么局部类定义在 C++ 中被归类为“非法”?
最佳答案
Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?
非法的,因为它们没有多大意义,无论是在函数内部定义函数还是在函数内部定义类,如 main()
。
但是您始终可以使用变通方法,例如:
- 对于函数,您始终可以使用 lambda ,它作为一个匿名的临时函数,可以在
main
中调用,也可以在函数参数中使用。
它可以在必要时被调用,随后像一次性函数一样被丢弃,但它完成了工作——无论你对函数有什么期望。
例子:
int main()
{
// Define within the scope of main()
auto temp = [](int x)
{ std::cout<< x;
}
temp(10); // call like a function
}
- 对于类,使用带有公共(public)访问说明符的静态函数(翻译单元的本地函数)(就像您在问题中所做的那样)。
例子:
int main()
{
class temp
{ public:
static void a()
{ std::cout<< 10;
}
};
temp::a();
}
两种情况的输出:10
如果有像上面那样的替代方法来定义 main()
中的函数/类/结构,那么就没有什么意义可言了他们合法。 ¯\_(ツ)_/¯
关于c++ - 为什么局部函数定义在 C++ 中是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290885/