4
圆括号未命名临时变量考虑下面的代码:在C++
struct Foo
{
};
struct Bar
{
explicit Bar(const Foo&)
{
}
};
int main()
{
Foo foo;
Bar bar(foo); // Okay.
Bar(foo); // Will not compile.
(Bar(foo)); // Okay. Unnamed temporary requires parenthesis.
}
为什么周围的临时版本括号需要?他们解决了什么模棱两可的问题?
我的预感是:我认为编译器看到Bar(foo)
作为函数的声明,但我不确定为什么会这样,因为foo
(实例)不是一个类型。因此,括号强制将上述内容视为表达式,而不是前向声明。
有趣。谢谢! – Forge95 2012-02-11 02:18:29