`List x;`和'List x()`之间有什么区别 [英] Is there any difference between `List x;` and `List x()`
问题描述
标题来自着名网站 C ++
作者声称以下两个代码示例之间有区别。
假设List是某个类的名称。然后函数f()声明一个名为x的局部List对象:
void f b $ b {
List x; // Local类名为x(List类)
...
}
< blockquote>
但是函数g()声明了一个函数x(),返回一个List:
void g()
{
List x(); //函数命名为x(返回一个List)
...
}
但是使用第二个变量是真的错了吗?
如果它真的是一个声明,不会编译器抱怨说你不能在函数中声明一个函数
如果它真的是一个声明不会编译器抱怨你不能声明函数内的函数。
当然不是。
这是最令人烦恼的解析,因此您可以可以声明函数。事实上,它代表编译器处理一个错误
List x();
作为变量声明。
但是使用第二个变量真的错了吗?
如果你想要一个变量,如果你想声明一个函数... kinda是的。你可以,但通常你会在函数范围之外。
The title comes from the famous site C++ FAQ by Marshall Cline.
The author claims that there is a difference between the following two code examples.
Suppose that List is the name of some class. Then function f() declares a local List object called x:
void f()
{
List x; // Local object named x (of class List)
...
}
But function g() declares a function called x() that returns a List:
void g()
{
List x(); // Function named x (that returns a List)
...
}
But is it really wrong to use the second variant?
And if it really is a declaration wouldn't the compiler complain that you cannot declare a function within a function?
And if it really is a declaration wouldn't the compiler complain that you cannot declare a function within a function.
Of course not. Because you can declare a function withing a function.
This is called most vexing parse and it's well documented. In fact, it would be an error on behalf of the compiler to treat
List x();
as a variable declaration.
But is it really wrong to use the second variant?
If you want a variable, then yes. If you want to declare a function... kinda yes. You can, but usually you'd do it outside of a function scope.
这篇关于`List x;`和'List x()`之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!