标签:style blog ar 使用 sp strong on div log
名称空间是为了更好的控制名称的作用域,以管理不同的类库,避免发生冲突。
1、创建名称空间
如下,使用namespace关键字创建了pers和debts两个名称空间。
#ifndef NAMESP_H_
#define NAMESP_H_
namespace pers
{
	const int LEN = 40;
	struct Person
	{
		char fname[LEN];
		char lname[LEN];
	};
	void GetPerson(Person &);
	void ShowPerson(const Person &);
}
namespace debts
{
	using namespace pers;
	struct Debt
	{
		Person name;
		double amount;
	};
	void GetDebts(Debt &);
	void ShowDebts(const Debt &);
	double SumDebts(const Debt arr[], int n);
}
#endif
名称空间可以是全局的,也可以位于另一个名称空间中,但不能位于代码块中。
分类:
(1)用户定义的名称空间(使用namespace关键字)
(2)全局名称空间 (不定义名称空间的情况下,都属于全局名称空间)
2、使用名称空间
(1)using声明
using std::cout;
using pers::Person
using声明使特定的标识符可用
(2)using编译指令
using编译指令使整个名称空间都可用。
如:
using namespace std;
using namespace pers;
注:
(1)使用using声明比使用using编译指令更安全
(2)优先使用域解析操作符(::)或using声明
(3)对于using声明,首选将其作用域设置为局部而不是全局。
标签:style blog ar 使用 sp strong on div log
原文地址:http://www.cnblogs.com/cmranger/p/4158718.html