【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;
}

猜你喜欢

转载自blog.csdn.net/Miss_Monster/article/details/84718848