一、命名空间介绍
namespace 命名空间主要用来解决命名冲突
1.命名空间下可以放函数、变量、结构体、类
2.命名空间必须定义在全局作用域下
3.命名空间可以嵌套命名空间
4.命名空间是开放的,可以随时往原先的命名空间添加内容
5.无名/匿名命名空间
6.命名空间可以起别名
二、具体代码实例
1.xyz.h
#pragma once
#include <iostream>
using namespace std;
namespace xyj
{
void monkeyKing();
}
2.xyz.cpp
#include "xyz.h"
void xyj::monkeyKing()
{
cout << "西游记里面的孙悟空" << endl;
}
3.king.h
#pragma once
#include <iostream>
using namespace std;
namespace king
{
void monkeyKing();
}
4.king.cpp
#include "king.h"
void king::monkeyKing()
{
cout << "王者荣耀里面的孙悟空" << endl;
}
5.main.cpp
#include <iostream>
#include "king.h"
#include "xyz.h"
using namespace std;
void testCout01()
{
xyj::monkeyKing();
king::monkeyKing();
}
namespace A
{
void func1();
int m_A = 20;
struct MyStruct
{
};
class MyClass
{
public:
MyClass();
~MyClass();
private:
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
namespace B
{
int m_A = 10;
}
}
void testCout02()
{
cout << "作用域B下的m_A:" << A::B::m_A << endl;
}
namespace A
{
int m_B = 123456;
}
void testCout03()
{
cout << "A下的m_A :" << A::m_A << "||||||" << "A下的m_B:" << A::m_B <<endl;
}
namespace
{
int m_C = 0;
int m_D = 0;
}
namespace LongLongName
{
int m_A = 90;
}
void testCout04()
{
namespace shortName = LongLongName;
cout <<"m_A:" <<LongLongName::m_A<<endl;
cout << "m_A:" << shortName::m_A << endl;
}
int main()
{
testCout01();
testCout02();
testCout03();
testCout04();
system("pause");
return 0;
}
main.cpp 代码拆分
namespace LongLongName
namespace shortName
namespace A
namespace B
testCout01()
testCout02()
testCout03()
testCout04()