我在 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)
是什么意思?到目前为止,我只看到函数声明如下:
Foo f( int );
和
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)
将被视为(参数的)声明而不是函数样式转换。