嵌套 if 中的范围歧义 [英] Scope ambiguity in nested if

查看:46
本文介绍了嵌套 if 中的范围歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个 Foo 类,例如

Let's say one has a class Foo such as

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

然后就可以了

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

现在我无法理解这里发生的作用域解析(我原以为重新声明 foo 会出现编译器错误).

Now I'm having trouble grasping the scope resolution going on here (I would've expected a compiler error for redeclaring foo).

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

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++ 很乐意让你声明一个同名的变量,只要它在嵌套的作用域内,所以没有歧义.

C++ is quite happy for you to declare a variable with the same name, as long as it is inside a nested scope so there is no ambiguity.

我希望 foo.bar() 在第二个 foo 上执行(它的作用域更近")

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

你说得对

但是我能保证它实际上与第一个 foo 是不同的对象吗?

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

是的

此外,它们是否在各自的 if 块末尾独立放置(调用它们的析构函数)?

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

是的

这篇关于嵌套 if 中的范围歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆