c++ - 最烦人的解析

标签 c++ most-vexing-parse

<分区>

我在 Cpp Quiz 看到了一个代码[问题 #38]

#include <iostream>

struct Foo
{
  Foo(int d) : x(d) {}
  int x;
};

int main() 
{ 
  double x = 3.14;

  Foo f( int(x) );

  std::cout << f.x << std::endl;

  return 0;
} 

据说这段代码格式错误,因为 Foo f( int(x) ); 将被视为函数声明而不是 Foo< 类型的对象声明.

据我所知,这是“最令人烦恼的解析”的一个实例。我的问题是语句 Foo f( int(x) ); 中的语法 int(x) 是什么意思?到目前为止,我只看到函数声明如下:

  1. Foo f( int );

  2. Foo f( int x );

它和Foo f( int x ); 一样吗?

最佳答案

what does this syntax int(x) in the statement Foo f( int(x) ); mean?

x 两边的括号是多余的,将被忽略。所以int(x)和这里的int x是一样的,意思是一个名为x的参数,类型是int .

Is it the same as Foo f( int x );?

是的。 Foo f( int(x) );,是一个名为f的函数声明,返回Foo,接受一个名为的参数x 类型为 int

这是标准的解释。 [dcl.ambig.res]/1 :

(强调我的)

The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in [stmt.ambig] can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in [stmt.ambig], the resolution is to consider any construct that could possibly be a declaration.

Note: A declaration can be explicitly disambiguated by adding parentheses around the argument. The ambiguity can be avoided by use of copy-initialization or list-initialization syntax, or by use of a non-function-style cast.

struct S {
  S(int);
};

void foo(double a) {
  S w(int(a));      // function declaration
  S x(int());       // function declaration
  S y((int(a)));    // object declaration
  S y((int)a);      // object declaration
  S z = int(a);     // object declaration
}

因此,int(x) 将被视为(参数的)声明而不是函数样式转换。

关于c++ - 最烦人的解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951362/

相关文章:

c++ - 在不带参数的函数声明中指定使用 void 是否解决了最令人烦恼的解析问题?

c++ - 移动构造函数和强异常保证

c++ - 声明指向 char 数组的指针数组

c++ - 没有互联网弹出窗口 Qt 和 QML(移动设备)

c++ - 如何在我的 "include path"中放入一些东西?

C++ 函数定义和变量声明不匹配?

c++ - 函数声明顺序在头文件中重要吗?

c++ - 设置 packaged_task 的正确方法

c++ - 将函数声明转换为变量定义的简单技巧