将变量声明为全局变量,然后声明为局部变量-Shadowing- [英] Declaring a variable as global and then as local -Shadowing-

查看:102
本文介绍了将变量声明为全局变量,然后声明为局部变量-Shadowing-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将变量声明为全局变量,然后将其重新声明为局部变量是什么意思?

What does it mean to declare a variable as global and then re-declare it as local like this:

int a = 0;
int main()
{
    int a = 7;
    return 0;
}

我在参考资料中看到了此示例,但我不理解.请考虑到我是C ++编程的初学者.

I saw this example in a reference, but I don't understand it. please put into consideration that I'm a beginner at programming with C++

推荐答案

这意味着在您的main方法中,如果仅使用a,则将引用该方法中声明的那个,因为它会阴影global one.要访问main中的global one,您需要通过::a访问.在其他方法中,如果要使用a,则将引用该文件中的每个方法的global.范围像这样工作,如果找不到变量,它就会去尝试在外部范围内找到,以此类推,直到全局范围.

This means that in your main method if you use only a, you will refer to that one which is declared in that method, because it shadows the global one. To access the global one within main, you need to access via ::a. Within other methods if you will use a, you will refer to that one which is global for every method in that file. Scopes work like this, if it doesn't find a variable, it goes and tries to find in the outer scope and so on to the global scope.

避免全局变量的一个建议

这篇关于将变量声明为全局变量,然后声明为局部变量-Shadowing-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆