获取变量的中间范围值

Get the middle scoped value of variable

本文关键字:范围 中间 变量 获取      更新时间:2023-10-16

假设这是一段代码,用于演示如何使用局部变量和全局变量。我试图向一个初级人员解释这一点,他问了我这个问题。

在下面的代码中,您应该如何从外部循环中获取"x"的值。在这种情况下,如何访问值为 2 的"x"。

#include<iostream>
using namespace std;
int x = 1;
void fun() {
  int x = 2;
  {
    int x = 3;
    cout << x << endl; // This will give 3
    cout << ::x << endl; // This will give 1
    // What should I write here to get x = 2.
  }
}
int main() {
  fun();
}

你不能。第一个x的名称已被第二个x隐藏。由于第一个x不属于命名空间(包括全局命名空间(、类或枚举,因此无法限定其名称,因此无法访问。