1 using namespace std; 2 namespace A { 3 int a = 100; 4 namespace B //嵌套一个命名空间B 5 { 6 int a = 20; 7 } 8 } 9 10 int a = 200;//定义一个全局变量 11 12 13 int main(int argc, char *argv[]) { 14 cout << "A::a =" << A::a << endl; //A::a =100 15 cout << "A::B::a =" << A::B::a << endl; //A::B::a =20 16 cout << "a =" << a << endl; //a =200 17 cout << "::a =" << ::a << endl; //::a =200 18 19 using namespace A; 20 cout << "a =" << a << endl; // Reference to 'a' is ambiguous // 命名空间冲突,编译期错误 21 cout << "::a =" << ::a << endl; //::a =200 22 23 int a = 30; 24 cout << "a =" << a << endl; //a =30 25 cout << "::a =" << ::a << endl; //::a =200 26 27 //即:全局变量 a 表达为 ::a,用于当有同名的局部变量时来区别两者。 28 29 using namespace A; 30 cout << "a =" << a << endl; // a =30 // 当有本地同名变量后,优先使用本地,冲突解除 31 cout << "::a =" << ::a << endl; //::a =200 32 33 34 return 0; 35 }