命名空间的用途
解决名称冲突
#include <iostream>
using namespace std;
namespace KingGlory{
void goAtk();
}
namespace LOL{
void goAtk();
}
void KingGlory::goAtk(){
cout << "崩坏3攻击实现" << endl;
}
void LOL::goAtk(){
cout << "LOL攻击实现" << endl;
}
void test01(){
KingGlory::goAtk();
LOL::goAtk();
}
int main(){
test01();
}
2.
命名空间可以放变量、函数、结构体、类…
namespace A{
int m_A;
void func();
struct Person{};
class Animal{};
}
- **
命名空间必须声明在全局作用域下
**
4.
命名空间可以嵌套命名空间
namespace B{
int m_A = 10;
namespace C{
int m_A = 20;
}
}
void test03(){
cout << "B space m_A =" << B::m_A << endl;
cout << "c space m_A =" << B::C::m_A << endl;
}
int main(){
test03();
}
命名空间是开放的,可以随时给命名空间添加新的成员
namespace B{
int m_A = 10;
}
namespace B{
int m_B = 100;
}
void test04(){
cout << "B space m_A = " << B::m_A << endl;
cout << "B space m_A = " << B::m_B << endl;
}
命名空间可以是匿名的
namespace{
int m_C = 1000;
int m_D = 2000;
}
void test05(){
cout << "m_C = " << m_C <<endl;
cout << "m_D = " << ::m_D << endl;
}
int main(){
test05();
}
命名空间可以起别名
namespace verylongName{
int m_E = 10000;
}
void test06(){
namespace veryShortName = verylongName;
cout << verylongName::m_E << endl;
cout << veryShortName::m_E << endl;
}
int main(){
test06();
}