C++(三)之namespace的作用

首先我们在CFree5中新建一个工程:

第一步:

工程中新建一个项目。

第二步:

把文件添加到项目中。

然后我们来讲解一下namespace的用法:

有如下用法:
  namespace : 主要的功能是用来解决命名冲突。
  1、namespace下面可以放函数、变量、结构体、类。 
  2、namespace可以嵌套使用 
  3、namespace必须定义在全局作用域下 
  4、namespace是开放的,可以随时向namespace中添加内容 
  5、匿名namespace相当于static修饰 
  6、namespace可以起别名 

 

上源码:

game1 game2是用来测试两个namespace是如何的区分的,其他功能均放到main文件中来测试了。

main文件:

/**
 * namespace : 主要的功能是用来解决命名冲突。
 * 1、namespace下面可以放函数、变量、结构体、类。 
 * 2、namespace可以嵌套使用 
 * 3、namespace必须定义在全局作用域下 
 * 4、namespace是开放的,可以随时向namespace中添加内容 
 * 5、匿名namespace相当于static修饰 
 * 6、namespace可以起别名 
 */

#include <iostream>

#include "game1.h"
#include "game2.h"

using namespace std;

//test01 不同的命名空间
void test01(void)
{
	LOL::goAtk();  			//LOL namespace下的 goAtk 
	
	KingGlory::goAtk(); 	//KingGlory namespace下的 goAtk 
} 


//
namespace A
{
	int m_A = 10;  //变量
	void f_A(); //函数 
	struct s_A{};  //结构体
	class A{};	//类 
	
	
	namespace B  //嵌套调用namespace 
	{
		int m_A = 20; 
	}
 	
} 

void test02(void)
{
	cout << "namespace 下面的m_A:" << A::B::m_A << endl;
}


//向namespace A中添加内容
namespace A
{
	int m_B = 30; 
}
 
void test03(void)
{
	cout << "A::m_B 的值是: " <<  A::m_B << endl;
}


//匿名namespace, 
namespace
{
	int m_C = 15;  //匿名namespace中,相当于static m_C,也就是本文件可以见 
	int m_D = 25; 
} 

void test04(void)
{
	cout << "m_C 的值:" << m_C << endl;
	cout << "m_D 的值:" << m_D << endl;
}


//namespace 起别名
namespace veryLongName
{
	int very_A = 13; 
} 

void test05(void)
{
	namespace veryShortName = veryLongName;
	
	cout << "veryShortName :: very_A  的值:" << veryShortName::very_A << endl;
	cout << "veryLongName :: very_A  的值:" << veryLongName::very_A << endl;
}

int main(void)
{

	cout << "test01: " << endl; 
	test01(); 
	cout << endl;
	
	cout << "test02: " << endl; 
	test02();
	cout << endl;
	
	cout << "test03: " << endl; 
	test03();
	cout << endl;
	
	cout << "test04: " << endl; 
	test04(); 
	cout << endl;
	
	cout << "test05: " << endl; 
	test05();
	cout << endl;
	
	return 0;
} 

game1.h

#ifndef __GAME1_H
#define __GAME1_H

#include <iostream>

using namespace std;
 
namespace LOL
{
	void goAtk();
} 


#endif /* __GAME1_H */

game1.cpp

#include "game1.h"

void LOL::goAtk()
{
	cout << "LOL 攻击实现!" << endl; 
}

game2.h

#ifndef __GAME2_H
#define __GAME2_H

#include <iostream>

using namespace std;

namespace KingGlory
{
	void goAtk();
} 

#endif  /* __GAME2_H */

game2.cpp

#include "game2.h"

void KingGlory::goAtk()
{
	cout << "KingGlory 攻击实现!" << endl; 
} 

测试结果:

发布了82 篇原创文章 · 获赞 2 · 访问量 3997

猜你喜欢

转载自blog.csdn.net/shao15232/article/details/103766485