【问题标题】:Access to redefined variables inside a nested block [duplicate]访问嵌套块内重新定义的变量[重复]
【发布时间】:2017-06-07 17:17:47
【问题描述】:

考虑下面的程序:

#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int i = 8;
          {
                int i = 7;
                cout << i << "\n";   // i = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other i declarations here?
          }
     }
     return 0;
}

在嵌套块内使用i 指的是i 的最后声明,因为后者隐藏了其他声明。为了使用全局i(main函数外的声明),我们可以使用::i

我想知道是否有办法在嵌套块内使用i 的其他声明。

【问题讨论】:

  • 简而言之:这是不可能的。所以不要这样做。
  • 没办法,如果需要访问外部作用域变量,请使用不同的名称
  • 你为什么要写这样的代码?
  • @CodyGray,只是好奇 :)

标签: c++


【解决方案1】:

声明一个新的变量名,类似于“j”而不是“i”。

#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int j = 8;
          {
                int j = 7;
                cout << j << "\n";   // j = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other 
       i declarations here?
          }
     }
     return 0;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多