C++ 访问上层作用域而不是全局

标签 c++ scope

您可以在下面找到我的代码及其输出。我应该在“SOMETHING”中使用什么前缀(或其他东西)来访问中级的 j (j==2)?

我试过了

main::j

但是没有用。

代码:

#include <iostream>
int j=3;//global
using std::cout;using std::endl;
int main(){
int j=2;//mid
cout<<"inside general main:\n";
cout<<"cout<<j---"<<j<<endl;//prints 2
cout<<"cout<<::j---"<<::j<<endl;//prints 3
cout<<"inside for loop:\n";
for(int i=0;i<1;i++){
    int j=1;//inside
    cout<<"cout<<j---"<<j<<endl;//prints 1
    cout<<"cout<<::j---"<<::j<<endl;//prints 3
    //cout<<"cout<<::j---"<<SOMETHING<<endl;//prints 2
}
return 0;
}

输出:

inside general main:
cout<<j---2
cout<<::j---3
inside for loop:
cout<<j---1
cout<<::j---3

最佳答案

没有引用本地范围的限定。

只是使用不同的名称。

关于C++ 访问上层作用域而不是全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39811574/

相关文章:

c# - 变量cfr的范围。 Pluralsight C# 测试

c - C 中带有 const 变量的数组大小

c++ - Cryptopp 致命信号 11

c++ - 在 C++ 中将对象存储在二维 Sprite 矩阵中

r - R 函数有没有办法判断它是从 `for` 还是 `while` 循环调用的?

函数混淆中的javascript变量范围

具有函数属性的 Javascript 对象有关 'this' 的详细信息

java - 带插值的仿射变换

c++ - 以下抽象工厂设计模式的实现是否正确?

c++ - 为什么 std::fstream 类不采用 std::string?