访问嵌套块中重新定义的变量

时间:2017-06-07 17:17:47

标签: c++

考虑以下计划:

#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的其他decalarations。

1 个答案:

答案 0 :(得分:0)

声明一个新的变量名称,类似于'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;
    }