问题
With
#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;
}
having the output
3 1 1
2 1
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".
回答1:
No you can't, a (2) is hidden.
Ref: 3.3.7/1
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
Ref: 3.4.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.
回答2:
Short answer: no. You are basically overriding the inherited scope of a locally, and it will use that local copy over any inherited ones.
Basically like a child object overriding a function or variable of the parent object, it will use it's copy of it regardless of what the parent had.
来源:https://stackoverflow.com/questions/5187891/accessing-variables-with-the-same-name-at-different-scopes