我对值初始化的尝试被解释为函数声明

我对值初始化的尝试被解释为函数声明

本文介绍了我对值初始化的尝试被解释为函数声明,为什么不是 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 的函数的声明,它带有一个指向返回 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 a(());解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:51
查看更多