C++之命名空间

为什么要有命名空间?

在C/C++中会有大量的函数,变量,类都被保存到全局作用域,很容易导致命名冲突,运行就会报错。

#include <stdio.h>
#include <stdlib.h>

int rand = 10;

int main()
{
	printf("%d\n", rand);
	return 0;
}

为了解决这个问题,引入命名空间。

命名空间的定义

命名空间的关键字是:namespace,后面跟命名空间的名字,再接一对{}即可,{}里就是命名空间的成员。

#include <stdio.h>
#include <stdlib.h>

namespace code
{
	int rand = 10;
}

int main()
{
	printf("%d\n", code::rand);
	return 0;
}

将rand变量放到code空间去,就不会重定义了。

命名空间还可以定义函数和类。

namespace code
{
	int rand = 10;
	int Add(int x, int y)
	{
		return x + y;
	}

	class A
	{
	public:
	private:
	};
}

 命名空间还可以嵌套

namespace N1
{
	namespace N2
	{

	}
}

并且同一个工程文件中的多个命名空间还会合并成同一个。

命名空间的使用

  • 加命名空间名称及作用域限定符
namespace code
{
	int rand = 10;
	int Add(int x, int y)
	{
		return x + y;
	}
}
int main()
{
	printf("%d\n", code::rand);
	return 0;
}
  • 使用using将命名空间中某个成员引入
using code::rand;
int main()
{
	printf("%d\n", rand);
	return 0;
}
  • 使用using namespace 命名空间名称 引入
using namespace code;
int main()
{
	printf("%d\n", rand);
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值