例子1
#include <iostream>
using namespace std;
// 第一个命名空间
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
}
// 第二个命名空间-嵌套的命名空间
namespace second_space{
void func(){
cout << "second_space" << endl;
}
namespace third_space{
void func(){
cout << "third_space" << endl;
}
void test(){
cout << "test" << endl;
}
}
}
using namespace first_space;
//using namespace second_space::third_space;//声明第三命名空间
int main (){
// 调用第一个命名空间中的函数
func();
// 调用第一个命名空间中的函数
first_space::func();
// 调用第二个命名空间中的函数
second_space::func();
// 无法在声明使用第二命名空间后调用第三个命名空间中的函数
second_space::test();//error!!!
return 0;
}
例子2 关于命名空间内变量和函数及全局变量的使用和作用域
#include <iostream>
using namespace std;
namespace A{
int a = 100;
namespace B{
int a =20;
}
}
int a = 200;//定义一个全局变量
int main(int argc, char *argv[]){
cout <<"A::a ="<< A::a << endl;
cout <<"A::B::a ="<<A::B::a << endl;
cout <<"a ="<<a << endl;
cout <<"::a ="<<::a << endl;
int a = 30;
cout <<"a ="<<a << endl;
cout <<"::a ="<<::a << endl;
return 0;
}
结果:
A::a =100
A::B::a =20
a =200 //全局变量a
::a =200
a =30 //局部变量a
::a =200
即:全局变量 a 表达为 ::a,用于当有同名的局部变量时来区别两者。
ref:https://www.runoob.com/cplusplus/cpp-namespaces.html