从嵌套块的预期块中访问变量 [英] accessing variables from an intended block of nested blocks
问题描述
在下面的程序中,如何从块C中的块A中检索aa的值?
我们只能使用范围解析运算符访问最外层的全局aa。
In the program below, how to retrieve value of aa from Block A in Block C? We can only access the outermost global aa using scope resolution operator.
已知的溶剂:
1.在不同的块$ b $中使用不同的指针b 2.在使用当前块的变量之前,先在父块中使用变量
Known solutoins: 1. Use different pointers in different blocks 2. Use the variable in parent block before using the current block's variable
我正在寻找其他替代解决方案
I am looking for any other alternative solution
我知道这不是好代码。
I know that this is not good code. Just curious in understanding how to achieve it.
#include <iostream>
#include <cstdio>
using namespace std;
// Global
int aa = 10;
int main()
{
// Main
int aa = 20;
{
// Block A
int aa = 30;
{
// Block B
int aa = 40;
{
// Block C
int aa = 50;
cout << "block C " << aa << endl;
cout << "block A " << ????? << endl;
cout << "global" << ::aa << endl;
}
cout << "block B " << aa << endl;
}
cout << "block A " << aa << endl;
}
cout << "main " << aa << endl;
return 0;
}
推荐答案
我知道这不是好代码。只是好奇地了解如何实现。
I know that this is not good code. Just curious in understanding how to achieve it.
您不能。
未经修饰使用变量 aa
将使用最接近范围的变量。
修饰使用变量 :: aa
,将使用函数外部作用域中的值。
装饰使用变量< NS> ::: aa
,将使用名称空间< NS>
范围内的那个。
Undecorated use of the variable aa
will use the one that is in the nearest scope.
Decorated use of the variable, ::aa
, will use the one that is in the scope outside the function.
Decorated use of the variable, <NS>::aa
, will use the one that is in the scope of the namespace <NS>
.
这篇关于从嵌套块的预期块中访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!