我想大家都见过这样的程序吧:
hello_world.c
#include <iostream>
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 <iostream>
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指令局限在很小的作用域中,这样他们的效用就会受到限制并且易于使用。类似的例子有
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
}
namespace second
{
double x = 3.1416;
}
int main () {
{
using namespace first;
cout << x << endl;
}
{
using namespace second;
cout << x << endl;
}
return 0;
}
输出是
5
3.1416
可以看到两个不同的namespace都被限制在了不同作用域中了,他们之间就没有冲突。
namespace也支持嵌套
#include <iostream>
namespace first
{
int a=10;
int b=20;
namespace second
{
double a=1.02;
double b=5.002;
void hello();
}
void second::hello()
{
std::cout <<"hello world"<<std::endl;
}
}
int main()
{
using namespace first;
std::cout<<second::a<<std::endl;
second::hello();
}
输出是
1.02
hello world
在namespace first中嵌套了namespace second,seond并不能直接使用,需要first来间接的使用。