不具名的命名空间(unnamed namespaces)

众所周知,命名空间是用来防止对象的重复定义的。
如下,编译不会出错:

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();
}
//在本地直接使用即可
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(){}
    }

This is called an unnamed or anonymous namespace and it is useful when you want to make variable declarations invisible to code in other files (i.e. give them internal linkage) without having to create a named namespace. All code in the same file can see the identifiers in an unnamed namespace but the identifiers, along with the namespace itself, are not visible outside that file—or more precisely outside the translation unit.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值