访问不同作用域的同名变量

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语句中访问等于2的'a',其中'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

名称可以被显式隐藏在同名声明中嵌套声明区域或派生区域类(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

类或命名空间的名称成员可以在 :: 之后引用范围解析运算符 (5.1)应用于嵌套名称说明符指定它的类或命名空间.在查找前面的名称期间:: 范围解析运算符,对象、函数和枚举器名称被忽略.如果找到的名字不是类名(第 9 条)或namespace-name (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.

这篇关于访问不同作用域的同名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:访问不同作用域的同名变量

基础教程推荐