我对值初始化的尝试被解释为函数声明,为什么不使用a(());?解决这个问题? [英] My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?

查看:67
本文介绍了我对值初始化的尝试被解释为函数声明,为什么不使用a(());?解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stack Overflow教给我的很多东西是所谓的最烦人的解析,经典地用诸如以下的行来演示

Among the many things Stack Overflow has taught me is what is known as the "most vexing parse", which is classically demonstrated with a line such as

A a(B()); //declares a function

虽然在大多数情况下,直观上这似乎是对象的声明<类型为 A 的code> a ,将临时 B 对象作为构造函数参数,它实际上是函数 a 的声明,返回 A ,并带有指向返回 B 本身不带任何参数。

While this, for most, intuitively appears to be the declaration of an object a of type A, taking a temporary B object as a constructor parameter, it's actually a declaration of a function a returning an A, taking a pointer to a function which returns B and itself takes no parameters. Similarly the line

A a(); //declares a function

也属于同一类,因为它声明了一个对象而不是对象功能。现在,在第一种情况下,此问题的通常解决方法是在 B()周围添加额外的括号/括号,因为编译器随后将其解释为对象的声明

also falls under the same category, since instead of an object, it declares a function. Now, in the first case, the usual workaround for this issue is to add an extra set of brackets/parenthesis around the B(), as the compiler will then interpret it as the declaration of an object

A a((B())); //declares an object

但是,在第二种情况下,执行相同操作会导致编译错误

However, in the second case, doing the same leads to a compile error

A a(()); //compile error

我的问题是,为什么?是的,我非常清楚正确的解决方法是将其更改为 A a; ,但是我很好奇知道多余的()在第一个示例中对编译器起作用,然后在第二个示例中重新应用时不起作用。 A a((B())); 解决方法是将特定异常写入标准吗?

My question is, why? Yes I'm very well aware that the correct 'workaround' is to change it to A a;, but I'm curious to know what it is that the extra () does for the compiler in the first example which then doesn't work when reapplying it in the second example. Is the A a((B())); workaround a specific exception written into the standard?

推荐答案

没有开明的答案,仅是因为C ++语言没有将其定义为有效的语法……实际上是通过语言的定义。

There is no enlightened answer, it's just because it's not defined as valid syntax by the C++ language... So it is so, by definition of the language.

如果其中包含表达式,则该表达式有效。例如:

If you do have an expression within then it is valid. For example:

 ((0));//compiles

更简单地说:因为(x)是有效的C ++表达式,而( )不是。

Even simpler put: because (x) is a valid C++ expression, while () is not.

要了解有关如何定义语言以及编译器如何工作的更多信息,您应该了解形式语言理论或更具体地说,是上下文无关文法(CFG )和相关材料(如有限状态机)。如果您对此感兴趣,尽管维基百科页面还不够用,您就必须拿一本书。

To learn more about how languages are defined, and how compilers work, you should learn about Formal language theory or more specifically Context Free Grammars (CFG) and related material like finite state machines. If you are interested in that though the wikipedia pages won't be enough, you'll have to get a book.

这篇关于我对值初始化的尝试被解释为函数声明,为什么不使用a(());?解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆