命名空間
一:命名空間的特點
用途:解決命名衝突問題
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;
} // 兩者的結果相等