Namespaces (C++)

Namespaces (C++)

The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files:

char func(char);
class String { ... };

// somelib.h
class String { ... };

With these definitions, it is impossible to use both header files in a single program; the String classes will clash.

A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier makes it less likely that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example:

namespace one {
   char func(char);
   class String { ... };
}

// somelib.h
namespace SomeLib {
   class String { ... };
}

Now the class names will not clash because they become one::String and SomeLib::String, respectively.

C++ does not allow compound names for namespaces.

// pluslang_namespace.cpp
// compile with: /c
// OK
namespace a {
   namespace b {
      int i;
   }
}

// not allowed
namespace c::d {   // C2653
   int i;
}

Declarations in the file scope of a translation unit, outside all namespaces, are still members of the global namespace.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值