且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将变量声明为全局变量,然后声明为局部变量-Shadowing-

更新时间:2022-06-23 22:50:13

这意味着在您的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.

避免全局变量的一个建议