Is there any difference between `List x;` and `List x()`

我只是一个虾纸丫 提交于 2019-12-18 06:48:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12297021/is-there-any-difference-between-list-x-and-list-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!