gpt4 book ai didi

c++ - 在 C++ 中将未命名的临时变量括起来

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:49 25 4
gpt4 key购买 nike

考虑以下代码:

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 (实例)不是类型。因此,括号强制将上述内容视为表达式,而不是前向声明。

最佳答案

恭喜您发现 most vexing parse .

Scott Meyers 描述如下:

In general, the [C++] language (thanks, unfortunately, to its history) will try to interpret any declaration made like this as the declaration of a function.

在你的例子中,引入括号消除了解析的歧义,迫使它成为本地的。

关于c++ - 在 C++ 中将未命名的临时变量括起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com