命名空间
一:命名空间的特点
用途:解决命名冲突问题
1.命名空间下可以放函数、变量、结构体、类
namespace A{
int a = 10; //定义了变量
void b(){ //定义了函数
}
struct test_struct { //定义了结构体
};
class Person{ //定义了类
};
}
2.命名空间必须定义在全局的作用域下
3.命名空间可以嵌套命名空间
namespace A{
namespace B{ //嵌套的命名空间
}
}
4.命名空间是开放的,随时可以往原先的命名空间中添加内容
namespace A{
int c = 10;
}
往之前的命名空间中添加内容时无需滑动鼠标找到之前的命名空间后再添加内容,只需要重写一个同名的命名空间并往其中添加内容即可。
//可以通过这个test函数测试其正确性
void test(){
cout << "命名空间A中的A="<<A::a << endl;
cout << "命名空间A中的A="<<A::B::a << endl;
cout << A::a << A::c << endl;
}
5.命名可以是无名的
namespace {
int d=10;
int e=20;
}
//相当于定义了static int d=10 和 static int e=20;
当写了无名的命名空间时相当于写了静态的全局变量
6.命名空间可以起别名
namespace C{
int a = 520;
}
void test1(){
namespace D = C;
cout << "命名空间C下的a=" << C::a << endl;
cout << "命名空间D下的a=" << D::a << endl;
} // 两者的结果相等