众所周知,命名空间是用来防止对象的重复定义的。
如下,编译不会出错:
namespace n1
{
int x;
}
namespace n2
{
int x;
}
//访问
n1.x;
n2.x;
上面是具名的名字空间,不具名的名字空间也是防止对象重复定义用,只是他没有名字而已。
//file1.cpp:
namespace
{
//变量x和方法fun只在file1.cpp可见
int x;
int fun();
}
//file2.cpp
namespace
{
int x;
int fun();
}
//在本地直接使用即可
void func()
{
x = 1;
}
不知道名字当然无法访问了。不具名空间依然是外链接的,但是外界由于不知道名字所以无法访问,这样就具有了内链接的特性。使用不具名空间是为了保持对象的局部性。
可以用不具名命名空间替代static(staitc是内链接的)。(你可以把两者看成等价的东西嘻)
不能在.h 文件中使用不具名命名空间。因为两个头文件都使用不具名命名空间定义了一样的对象,包含进来依然会有冲突。
MSDN:
anonymous or unnamed namespaces
You can create an explicit namespace but not give it a name:
namespace
{
int MyFunc(){}
}