在c++中怎么创建命名空间

什么是命名空间呢?举一个现实中的例子,命名空间就像是一个企业,每个企业都有自己的员工。在这里假设每一个员工代表一个类,于是每一个命名空间中都包含若干个类。优于命名空间不同,编译器就可以将同名的类区别开来。这就像企业A中有个叫“张三”,企业B也有个叫“张三”的。但是由于两个企业不同,人们还是可以把两个人区分开来。

使用命名空间的方式有以下三种:

方法一:

#include"iostream"

namespace hehe
{
	using std::endl;
	using std::cout;
	void fun()
	{
		cout << "fun in hehe" << endl;
	}
}
int main()
{
	using namespace hehe;
	fun();
	return 0;
}

输出结果如下:

fun in hehe

请按任意键继续. . .

 

方法二:

#include"iostream"

namespace hehe
{
	using std::endl;
	using std::cout;
	void fun()
	{
		cout << "fun in hehe" << endl;
	}
	class X{
	public:
		static void fun()
		{
			cout << "fun in hehe::X" << endl;
		}
	};
}
int main()
{
	using namespace hehe;
	hehe::fun();
	hehe::X::fun();
	return 0;
}
输出结果如下:

fun in hehe
fun in hehe::X
请按任意键继续. . .

方法三:

#include"iostream"

namespace hehe
{
	using std::endl;
	using std::cout;
	void fun()
	{
		cout << "fun in hehe" << endl;
	}
}

namespace hoho
{
	using std::endl;
	using std::cout;
	void fun()
	{
		cout << "fun in hoho" << endl;
	}
}
int main()
{
	using namespace hehe;
	using hoho::fun;
	hehe::fun();
	fun();
	return 0;
} 
输出结果如下:

fun in hehe
fun in hoho
请按任意键继续. . .

对以上三种方法进行对比,可以得出一下结果:

①如方法一所示,使用using语句打开命名空间后,在后面的程序中,程序员不用再次输入命名空间的名字,但是使用using打开命名空间后,后面的命名空间讲默认为现有的命名空间,这样其他命名空间中同名的函数便不能直接使用,除非使用作用域标识符,负责会产生编译错误。

②方法二中使用作用域标识符打开命名空间的好处是,被打开的命名空间将不会对程序现有的命名空间造成任何影响。但是程序员每次要输入命名空间的名字,当命名空间名字很长时将会影响程序的可读性。

③方法三中使用申明语句似乎是前面两种方法的折中,既不需要输入较长的命名空间名,又不会对现有的命名空间造成影响。但是也有致命的缺点,即程序员必须记住所设申明的命名空间的名字,一旦忘记,后果不堪设想。

命名空间的增补操作如下:

#include"iostream"

namespace hehe
{
	using std::endl;
	using std::cout;
	void fun1()
	{
		cout << "fun1 in hehe" << endl;
	}
}
namespace hehe{
	void fun2()
	{
		cout << "fun2 in hehe" << endl;

	}
}
int main()
{
	using namespace hehe;
	fun1();
	fun2();
	return 0;
}
输出结果如下:

fun1 in hehe
fun2 in hehe
请按任意键继续. . .


有的命名空间名字比较长,也可以使用如下语句讲名字空间的名字改变:

namespace h=hehe;

  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值