在不同的范围访问具有相同名称的变量 [英] Accessing variables with the same name at different scopes
问题描述
使用
#include <iostream>
using namespace std;
int a = 1;
int main()
{
int a = 2;
if(true)
{
int a = 3;
cout << a
<< " " << ::a // Can I access a = 2 here?
<< " " << ::a << endl;
}
cout << a << " " << ::a << endl;
}
输出
3 1 1
2 1
有一种方法可以在if语句中访问'a'等于2,其中'a'等于3,输出
Is there a way to access the 'a' equal to 2 inside the if statement where there is the 'a' equal to 3, with the output
3 2 1
2 1
请注意 :我知道这应该不应该做(和代码不应该到达我需要问的点)。
Note: I know this should not be done (and the code should not get to the point where I need to ask). This question is more "can it be done".
推荐答案
不,你不能, (2)隐藏。
No you can't, a (2) is hidden.
参考:3.3.7 / 1
Ref: 3.3.7/1
可以通过在
嵌套的声明性区域或派生的
类(10.2)中显式的
声明来隐藏名称。
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
参考:3.4.3 / 1
Ref: 3.4.3/1
类或命名空间的名称
成员可以引用::
范围解析运算符(5.1)
应用于指定其类或命名空间的嵌套名称说明符
。
在查找
之前的名称时,:: scope解析操作符,
对象,函数和枚举器名称
将被忽略。如果找到的名字不是
a类名(第9节)或
命名空间名(7.3.1),程序是
格式错误。
The name of a class or namespace member can be referred to after the :: scope resolution operator (5.1) applied to a nested-name-specifier that nominates its class or namespace. During the lookup for a name preceding the :: scope resolution operator, object, function, and enumerator names are ignored. If the name found is not a class-name (clause 9) or namespace-name (7.3.1), the program is ill-formed.
这篇关于在不同的范围访问具有相同名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!