简体   繁体   English

当“全局”,“本地”和“非常本地”变量存在同名时,如何访问“本地”变量

[英]How to access “local” variable when a “global”, “local” and “very local” variable exist having same name

int i = 1;
int main()
{
    int i = 2;
    {
        int i = 3;
        cout << ::i << endl;  //i want to print 2, neither 1 nor 3
    }
    system("pause");
    return 0;
}

I want to print 2. By default, cout << i << endl; 我想打印2.默认情况下,cout << i << endl; prints 3 and cout << ::i << endl; print 3和cout << :: i << endl; prints 1. 打印1。

There is no way to refer to a local name when it has been hidden by another local name in a nested scope (such as the i with value 2 by the i with the value 3). 当嵌套范围中的另一个本地名称隐藏了本地名称时(例如i的值为2且值为3的i ,无法引用本地名称。 The best you can do is create a reference to it while it's still in scope: 您可以做的最好的事情是在它仍处于范围内时创建对它的引用:

int main()
{
    int i = 2;
    int& middle_i = i;
    {
        int i = 3;
        cout << middle_i << endl;  //will print 2
    }
    system("pause");
    return 0;
}

Of course, the actually correct solution is not to hide names you need to access, so rename one of the local i variables. 当然,实际上正确的解决方案不是隐藏您需要访问的名称,因此重命名其中一个本地i变量。


Since the question is also tagged c , be aware that C lacks both references and the scope resolution operator ( :: ), so in C you're stuck with using a pointer (even worse than a reference in this regard), or following the "actually correct solution" even strongly and not hiding any names you intend to use. 由于问题也被标记为c ,请注意C缺少引用和范围解析运算符( :: ,所以在C中你仍然坚持使用指针(甚至比这方面的引用更差),或者跟随“实际上正确的解决方案”甚至强烈,并没有隐藏任何你打算使用的名称。

You may be misinterpreting the concept of scopes. 您可能会误解范围的概念。

Local variables with the same name always have the priority. 具有相同名称的局部变量始终具有优先级。 It just doesn't make sense otherwise, how will the compiler know which variable you are referencing to? 它只是没有意义,编译器将如何知道您引用的变量? It is considered bad practice to use variables with the same name within the same parent scope and it is evident why. 在同一父范围内使用具有相同名称的变量被认为是不好的做法,这很明显。 Either reuse the same variable or write another function to be called. 重用相同的变量或编写另一个要调用的函数。

You can create a pointer to access the outer variable and since there is an answer regarding C++ I will give an example in C 您可以创建一个指针来访问外部变量,因为有关于C ++的答案,我将在C中给出一个示例

int i = 1;
int* p;
int main()
{
    int i = 2;
    p = &i;
    {
        int i = 3;
        // print *p
    }
    system("pause");
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM