我们应该知道传统的C++只有一个全局的namespace,但是由于现在的程序的规模越来越大,程序的分工越来越细,全局作用域变得越来越拥挤,每个人都可能使用相同的名字来实现不同的库,于是程序员在合并程序的时候就会可能出现名字的冲突。namespace引入了复杂性,解决了这个问题。namespace允许像类,对象,函数聚集在一个名字下。本质上讲namespace是对全局作用域的细分。
我想大家都见过这样的程序吧:
hello_world.c
#include
using namespace std;
int main()
{
printf("hello world !");
return 0;
}
我想很多人对namespace的了解也就这么多了但是namespace远不止如此,让我们再多了解一下namespace
namespace的格式基本格式是namespace identifier
{
entities;
}
举个例子,
namespace exp
{
int a,b;
}
有点类似于类,但完全是两种不同的类型。
为了在namespace外使用namespace内的变量我们使用::操作符,如下
exp::a
exp::b
使用namespace可以有效的避免重定义的问题 #include
using namespace std;
namespace first
{
int var = 5;
}
namespace second
{
double var = 3.1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
结果是
5
3.1416
两个全局变量都是名字都是var,但是他们不在同一个namespace中所以没有冲突。
关键字using可以帮助从namespace中引入名字到当前的声明区域 #include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return 0;
}
输出是
5
2.7183
10
3.1416
就如我们所指定的第一个x是first::x,y是second.y
using也可以导入整个的namespace #include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return 0;
}
输出是
5
10
3.1416
2.7183