<namespace>关于C++命名空间的使用

609 阅读2分钟

一、命名空间介绍

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命名空间主要用途 用来解决命名冲突
//1.命名空间下可以放函数、变量、结构体、类
//2.命名空间必须定义在全局作用域下
//3.命名空间可以嵌套命名空间
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()
{
	//输出作用域B下的m_A;
	cout << "作用域B下的m_A:" << A::B::m_A << endl;
}
//4.命名空间是开放的,可以随时往原先的命名空间添加内容
namespace A //此命名空间会和上面的命名空间进行合并而不是覆盖
{
	int m_B = 123456;
}

void testCout03()
{
	cout << "A下的m_A :" << A::m_A << "||||||" << "A下的m_B:" << A::m_B <<endl;
}

//5.无名/匿名命名空间
namespace
{
	int m_C = 0;
	int m_D = 0;
}
// 当写了无名命名空间,相当于写了 static int m_C;static int m_D;
//只能在当前文件内使用

//6.命名空间可以起别名
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  //命名空间LongLongName  
namespace shortName     //命名空间LongLongName的别名
namespace A  //命名空间A
namespace B  //命名空间B
testCout01() //调用不同命名空间下的 同一个名字的函数
testCout02() //输出作用域B下的m_A
testCout03() //输出A下的变量m_A 和 m_B
testCout04() //展示别名的作用效果