【C++】命名空间的使用

命名空间的使用主要有三种方式:

1.指定它属于该命名空间

如下,用namespace指定,搭配域作用限定符就可以了。 

namespace N
{
	int printf = 100;
	int strstr = 200;
}

int main()
{
	
	printf("%d\n",N::strstr);
	printf("%d\n",N::printf);
	system("pause");
	return 0;
}

2. 使用using namespace 命名空间名称引入

使用using namespace之后相当于把N中的内容全部展开在全局作用域,这时这段代码跑不过,因为这里面的内容可能会和其他东西有冲突,比如关键字和函数名之类的。所以一般不建议这样使用。

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

namespace N
{
	int printf = 100;
	int strstr = 200;
}

using namespace N;

int main()
{
	
	printf("%d\n",N::strstr);
	printf("%d\n",N::printf);
	system("pause");
	return 0;
}

 那么什么时候可以用呢?就是下面这段代码,当你定义的是很简单的不会产生冲突的变量时可以使用 using namespace

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

namespace N
{
	int q = 10;
}

using namespace N;

int main()
{
	printf("%d\n", q);//这两种方法都可以
	printf("%d\n", N::q);
	system("pause");
	return 0;
}

3. 使用using将指定的命名空间中成员引入

先来看一段代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace N
{
	int q = 10;
	int strstr = 100;
}

using namespace N;

int main()
{
	printf("%d\n", q);
	printf("%d\n", strstr);
	system("pause");
	return 0;
}

using namespace可以把内容展开,想打印 q ,但是在上面这段代码里使用的话,会把strstr也展开,这时就会产生冲突。所以有了 using 这个用法。指定只展开 q 。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace N
{
	int q = 10;
	int strstr = 100;
}
using N::q;
int main()
{
	printf("%d\n", q);
	printf("%d\n", N::strstr);
	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值