gpt4 book ai didi

c++ - 嵌套 if 中的范围歧义

转载 作者:太空狗 更新时间:2023-10-29 23:31:07 25 4
gpt4 key购买 nike

假设有一个 Foo 类,例如

class Foo {
public:
void bar();
operator bool() const { return true; }
};

然后就可以了

if(Foo foo = Foo())
{
if(Foo foo = Foo())
{
foo.bar();
}
}

现在我无法理解这里正在进行的范围解析(我本以为重新声明 foo 会出现编译器错误)。

我希望 foo.bar() 在第二个 foo 上执行(它的范围“更近”),但我能保证它实际上是与第一个 foo 不同的对象吗?此外,它们是否在各自的 if block 末尾独立处理(调用它们的析构函数)?

最佳答案

C++ 很高兴您声明一个具有相同名称的变量,只要它在嵌套范围内就不会出现歧义。

I expect foo.bar() to execute on the second foo (its scope is "closer")

你是对的

but am I garanteed that it's actually a different object than the first foo?

Furthermore, are they each independently disposed (their destructor called) at the end of their respective if blocks?

关于c++ - 嵌套 if 中的范围歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301629/

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