这是代码:
#include <iostream>
using namespace std;
int x = 1;
void fun()
{
int x = 2;
{
int x = 3;
cout<<::x<<endl;
}
}
int main()
{
fun();
return 0;
}
我想知道的是,有什么方法可以在函数fun内的大括号中访问值为2的x。当我写x时,它显示3,而:: x时,它显示1。因此,如何访问具有值2的x,以及如何将其称为全局变量或局部变量。
谢谢
编辑1:只问知识,想知道这种事情是否可能。
我想知道的是,有什么方法可以在函数fun内的大括号中访问值为2的x。
无法访问它。唯一可以访问它的“ hack”是:
int x;
{
int &xOuter = x;
int x;
// use xOuter here to access x of outer scope
}
我们称之为全局变量还是局部变量。
这是一个局部变量。
我建议您反对这种做法,因为这会造成混乱。为了避免这种情况,请使用gcc之类的编译器选项-Wshadow
来针对此类情况发出警告。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句