分析:结果是100,::x表示访问全局变量
test.cpp
static int x1 = 100;main.cpp
#include <iostream> using namespace std; namespace { int x1 = 999; }; void main() { cout << x1 << endl; //999 cout << ::x1 << endl; //999 cin.get(); }结果:999
分析:static限制test.cpp里面的x1的作用域为当前文件,因此在main.cpp中无法看到test.cpp定义的x1,从而::x访问的就是main.cpp里面的x1.
三、extern与匿名命名空间
test.cpp
int x1 = 100;main.cpp
#include <iostream> using namespace std; extern int x1; namespace { int x1 = 999; }; void main() { cout << ::x1 << endl; //100 cin.get(); }结果:100
分析:extern声明使用外部变量,此时把test.cpp链接到了main.cpp里面去了,此时的x1在main.cpp里面相当于全局变量,因此::x是100.
总结:
