最烦琐的解析:为什么不A(());工作? [英] Most vexing parse: why doesn't A a(()); work?

查看:134
本文介绍了最烦琐的解析:为什么不A(());工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< p> Stack Overflow所教导的许多东西是所谓的最烦琐的解析,它经典地用诸如

之类的行来表示。

  A a(B()); //声明一个函数

虽然这种方式直观上似乎是一个对象的声明 a 类型 a ,将临时 B 构造函数参数,它实际上是一个函数的声明 a 返回一个 A ,指向一个函数, code> B ,它本身没有参数。类似的行

  A a(); //声明一个函数

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

  A a((B())); //声明一个对象

但是,在第二种情况下, / p>

  A a(()); //编译错误

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

解决方案

没有开明的答案,只是因为它没有被C ++语言定义为有效的语法...所以它是这样,根据语言的定义。



如果你有一个表达式,那么它是有效的。例如:

 ((0)); //编译

要详细了解语言是如何定义的,以及编译器如何工作,您应该了解 Formal language theory or more specifically Context Free Grammars(CFG)和相关材料,如有限状态机。如果你有兴趣,虽然维基百科页面是不够的,你必须得到一本书。


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

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

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

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?

解决方案

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

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天全站免登陆