天天看點

C++(三)之namespace的作用

首先我們在CFree5中建立一個工程:

第一步:

C++(三)之namespace的作用

工程中建立一個項目。

第二步:

C++(三)之namespace的作用

把檔案添加到項目中。

然後我們來講解一下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; 
} 
           

測試結果:

C++(三)之namespace的作用