c++中的局部变量和全局变量重名时取值问题
局部变量在使用时会屏蔽全局变量。要用全局变量,需要使用"::".
局部变量可以与全局变量同名,在函数内引用这个变量时,会用到同名的局部变量,而不会用到全局变量。对于有些编译器而言,在同一个函数内可以定义多个同名的局部变量,比如在两个循环体内都定义一个同名的局部变量,而那个局部变量的作用域就在那个循环体内。
#include<iostream>
using namespace std;
void test();
int i = 1;
int main()
{
int i = 2;
cout<<"global i = "<<::i<<" "<<"address = "<<&::i<<endl;
cout<<"main() i = "<<i<<" "<<"address = "<<&i<<endl;
test();
{
cout<<"main() i = "<<i<<" "<<"address = "<<&i<<endl;
int i = 3;
cout<<"local i = "<<i<<" "<<"address = "<<&i<<endl;
}
}
void test()
{
int i = 4;
cout<<"test() i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"global i = "<<::i<<" "<<"address = "<<&::i<<endl;
}
using namespace std;
void test();
int i = 1;
int main()
{
int i = 2;
cout<<"global i = "<<::i<<" "<<"address = "<<&::i<<endl;
cout<<"main() i = "<<i<<" "<<"address = "<<&i<<endl;
test();
{
cout<<"main() i = "<<i<<" "<<"address = "<<&i<<endl;
int i = 3;
cout<<"local i = "<<i<<" "<<"address = "<<&i<<endl;
}
}
void test()
{
int i = 4;
cout<<"test() i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"global i = "<<::i<<" "<<"address = "<<&::i<<endl;
}