转自:http://fxl.blogbus.com/logs/1444119.html
namespace test{
int age;
char name[20];
void other();
namespace test1{
int other;
void other();
}
}
1.名字空间可以是全局的,也可一位于其他名字空间中,但不能位于代码块中.名字空间是开放的,所以可以把名称加入到已有的名字空间中去.也可以在名字空间中使用 using 声明和 using 编译指令
namespace test{
using namespace test3;
}
2.c++提供了两种简化使用名字空间的方法 当然我们可以直接使用名字空间
test::test1::other();
using 声明 和 using 编译指令 用法如下:
using test::test1::other(); // 使得other 可用
using namespace test; // 使得test的名字空间中名称都可用
using 声明将把特定的名称添加到它所属的声明区域中,并且将会覆盖相应的变量,但是编译器不允许使用两个using 声明指向相同的名称
如 using test::other();
using test::test1::other() // not allow
3.一般来说,使用using声明比使用using 编译指令更加安全.因为当使用using声明,这是由于当它导入指定的名称,如果该名称和局部变量发生冲突是,编译器将发出指示,但是如果使用using编译指令的花,局部变量将覆盖名字空间版本.编译器不将发出警告
4.可以给名字空间创建别名
namespace mtest=test::test1
using mtest::other()
5.未命名的名字空间
namespace{
double ice;
int bandcount;
}
该声明中的名称的潜在作用域从声明点到该声明结束域.不过由于未命名的名字空间无法使用using声明和using 编译指令来使其在其他地方可用,因此不能在其所属文件的之外的文件使用该空间中的名称.这种方法可以替代连接性为内部的静态变量.c++ 也赞成这样做.即不赞成使用static
static int counts;
int other();
int main(){
....
}
int other(){
......
}
应该这样做:
namespace{
int counts;
}
int other();
int main(){
....
}
int other(){
......
}