c++命名空间

命名空间:c++中由用户命名的作用域,用来处理程序中的命名冲突。

命名空间一般是处在全局作用域中,当然,全局作用域中还有函数,全局变量等。

命名空间是这样定义的:

namespace N
{
	int test1;
	int test2;
}
这就是命名空间为N。命名空间有以下特点:

(1)可以在多个.cpp文件下同时生成namespace N;此时都会合并在同一个命名空间中。

(2)命名空间可嵌套。

如下:

namespace N
{
	int test1;
<span>	</span>int test2;
<span style="white-space:pre">	</span>namespace N1
<span style="white-space:pre">	</span>{
<span style="white-space:pre">	</span>	int test1;
		int test2;
<span style="white-space:pre">	</span>}
}
那么如果你要使用其中的变量呢?

(1)使用作用域限定符

#include<iostream>
namespace N
{
	int test1;
	int test2;
	namespace N1
	{
		int test1;
		int test2;
	}
}
int test1 = 30;
int main()
{
	N::test1 = 10;       //命名空间为N中的test1
	N::N1::test1 = 20;   //命名空间为N1中的test1
	std::cout<<N::test1<<std::endl;
	std::cout<<N::N1::test1<<std::endl;
	std::cout<<::test1<<std::endl;  //全局变量test1
	system("pause");
	return 0;
}

结果:


在这里用到了作用域限定符来标志你具体使用的变量。对于嵌套的命名空间,可一层一层的访问。

当然,还有另一种访问方式:

(2)使用using namespace + 命名空间名

#include<iostream>
namespace N
{
	int test1;
	int test2;
	namespace N1
	{
		int test1;
		int test2;
	}
}
using namespace N;
int main()
{
	test1 = 10;       //命名空间为N中的test1
	N1::test1 = 20;   //命名空间为N1中的test1
	std::cout<<test1<<std::endl;
	std::cout<<N1::test1<<std::endl;
	system("pause");
	return 0;
}
结果:


当你想单独使用某一个变量时,还可以这样声明一下。

#include<iostream>
namespace N
{
	int test1;
	int test2;
	namespace N1
	{
		int test1;
		int test2;
	}
}
using  N::N1::test1;          //直接使用test1
int main()
{
	test1 = 10;       //命名空间为N1中的test1
	std::cout<<test1<<std::endl;
	system("pause");
	return 0;
}
结果:



(3)当命名空间没名字时,该怎么使用?

#include<iostream>
namespace
{
	int test1;
	int test2;
	namespace N1
	{
		int test1;
		int test2;
	}
}
int main()
{
	test1 = 10;       //命名空间为N中的test1
	N1::test1 = 20;
	std::cout<<test1<<std::endl;
	std::cout<<N1::test1<<std::endl;
	system("pause");
	return 0;
}
结果:



当命名空间没名字时,也可直接使用,此时相当于全局变量。但是空间中的变量只在当前文件中可见。这时我们就会想到static(存在于静态区)。


static关键字用于修改标识符的链接属性。外部链接属性变为内部链接属性。只在当前文件可使用。

当它用于代码块内部的变量声明时,static关键字用于修改变量的存储类型,自动变量(auto)变为静态变量(static)。属性和作用域不受影响。

再回归到命名空间来说,c++中我们会用到最基本的输入输出(cin,cout),而cin,cout等都在std命名空间里,所以我们c++中一般定义:

#include<iostream>

using namespace std;

如果不说明using namespace std;我们就会用到作用域限定符std::cin,std::cout,std::endl;等等。










  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值