获取变量的中间范围值
Get the middle scoped value of variable
假设这是一段代码,用于演示如何使用局部变量和全局变量。我试图向一个初级人员解释这一点,他问了我这个问题。
在下面的代码中,您应该如何从外部循环中获取"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
不属于命名空间(包括全局命名空间(、类或枚举,因此无法限定其名称,因此无法访问。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 2D数组来自文本输入,中间有空格
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- 从函数返回范围视图时,带有std::span:中间对象所有权的C++Ranges-v3
- 从大范围内生成一个随机数,但从大范围的中间开始生成较小的范围
- 获取变量的中间范围值