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

  • 命名空间

在C/C++中,变量、函数和后面要学到的类都是大量存在的,这些变量、函数和类的名称将都存在于全局作用域中,可能会导致很多冲突。使用命名空间的目的,是对标识符的名称进行本地化,以避免命名冲突或名字污染,namespace关键字的出现就是针对这种问题的。

  • 命名空间定义

定义命名空间,需要使用到namespace关键字,后面跟命名空间的名字,然后接一对{}即可,{}中即为命名空间的成员。

  • 命名空间用法

要说命名空间,首先得知道一个概念:域作用限定符,来看一个代码:

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

int a = 10;
int main()
{
	int a = 20;
	printf("%d\n", a);
	printf("hello world\n");
	return 0;
}

这个代码中a输出的是多少?,一运行,发现输出的a是20,毫无疑问,这是因为,我们知道在访问时,遵循就近原则。那如果我就是想访问main函数外面的a呢?这时候,我们只需给a加上域作用限定符(::)就可以访问到了,即

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

int a = 10;//全局变量(域)
int main()
{
	int a = 20;
	printf("%d\n", ::a);//域作用限定符前面没有东西,就默认是全局域
	printf("hello world\n");
	system("pause");
	return 0;
}

引入了域作用限定符,命名空间就好理解了。我们知道在c语言中,定义变量的时候,一般不能使用C语言关键字来定义变量,如果一旦定义了,就会出现变量重定义的问题,为了解决这个问题,在c++中就有了命名空间。

  • 命名空间三种用法:

  • (1)命名空间里面成员不展开,需要什么,指定什么(加命名空间名称及作用域限定符)
#include <iostream>

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

namespace bit//命名空间
{
	int strstr = 10;//命名空间成员
	int printf = 20;//命名空间成员
}
int main()
{
	int a = 20;
	printf("%d\n", bit::printf);//指定printf属于bit这个域
	printf("%d\n",bit::strstr);//指定strstr属于bit这个域
	system("pause");
	return 0;
}

分析:因为printf和strstr分别是包在<stdio.h>和<string.h>里面,如果不适用命名空间指定的话,代码肯定是跑不过的。

  • (2)展开命名空间里面的全部成员(使用using namespace+命名空间名称引入)
#include <iostream>

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

namespace bit
{
	int strstr = 10;
	int printf = 20;
}
using namespace bit;//把bit这个命名空间里面的东西全部展出来
int main()
{
	int a = 20;
	printf("%d\n", bit::printf);
	printf("%d\n",bit::strstr);
	system("pause");
	return 0;
}

分析:这时代码肯定跑不过,会出现命名冲突的问题。需要说明的是一般我们很少使用把命名空间全部展开这种方式。那么什么时候才适合用它呢?就是bit里面定义的东西跟外面的东西没有冲突时,才把它展开。

举例:比如,我们要多次访问a,这时,就可以把a展开了

#include <iostream>

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

namespace bit
{
	/*int strstr = 10;
	int printf = 20;*/
	int a = 20;
}
using namespace bit;//把bit这个命名空间里面的东西全部展出来
int main()
{
	printf("%d\n", a);
	printf("%d\n",bit::a);//这样也是可以的
	system("pause");
	return 0;
}

分析:此时展开命名空间。就可以直接访问a

  • (3)展开命名空间部分内容(使用using 将命名空间中部分内容引入)
#include <iostream>

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

namespace bit
{
	int strstr = 10;
	int a = 10;
}
using bit::a;//指定把bit里面的a展出来
int main()
{
	printf("%d\n", a);
	system("pause");
	return 0;
}

分析:此时想访问a,又不能用using namespace bit;,这样会出现命名冲突,但是使用using bit::a,指定把bit里面的a展出来,就可以正常访问a了

以上就是关于命名空间的三种用法。

最后一个要说明的是:命名空间里面的内容,即可以定义变量,也可以定义函数,还可以进行嵌套。

注意:一个命名空间就是定义了一个新的作用域,命名空间中的所有内容都局限于该命名空间中。

猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/83868148
今日推荐