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

查看:15
本文介绍了我对值初始化的尝试被解释为函数声明,为什么不 A 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 类型的对象 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) 和相关材料,如有限状态机.如果您对此感兴趣,尽管 wikipedia 页面还不够,但您必须得到一本书.

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 a(());解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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