C ++命名空间,与Java包的比较 [英] C++ Namespaces, comparison to Java packages

查看:418
本文介绍了C ++命名空间,与Java包的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近做了一堆Java编码,并已经习惯于非常具体的包命名系统,使用深​​层嵌套。 com.company.project.db 。这在Java,AS3 / Flex和C#中工作得很好。我已经看到了在C ++中应用的相同的范例,但我也听说将C ++命名空间视为与Java包的直接对应是很糟糕的。

I've done a bunch of Java coding recently and have got used to very specific package naming systems, with deep nesting e.g. com.company.project.db. This works fine in Java, AS3/Flex and C#. I've seen the same paradigm applied in C++ too, but I've also heard that it's bad to view C++ namespaces as direct counterparts to Java packages.

这是真的,为什么?命名空间/包是如何和不同的?

Is that true, and why? How are namespaces/packages alike and different? What problems are likely to be seen if you do use deep nested namespaces?

推荐答案

在C ++命名空间中只是将可用的名称。 Java包是关于模块的。命名层次只是它的一个方面。

In C++ namespaces are just about partitioning the available names. Java packages are about modules. The naming hierarchy is just one aspect of it.

在C ++中嵌套的命名空间没有什么错,除了它们通常不需要,因为后面没有模块系统,额外的层只是增加了噪声。
通常有足够的一两个级别的命名空间,内部细节的奇怪额外级别(通常只是详细信息)。

There's nothing wrong, per-se, with deeply nested namespaces in C++, except that they're not normally necessary as there's no module system behind them, and the extra layers just add noise. It's usually sufficient to have one or two levels of namespace, with the odd extra level for internal details (often just called Details).

规则到C ++命名空间,如果过度使用可能会抓住你 - 例如依赖于参数的查找,以及解析到的规则父级别。 WRT后者,取:

There are also extra rules to C++ namespaces that may catch you out if overused - such as argument-dependent-lookup, and the rules around resolving to parent levels. WRT the latter, take:

namespace a{ namespace b{ int x; } }
namespace b{ string x; }
namespace a
{
  b::x = 42;
}

这是合法的吗?它是明显发生了什么?
您需要知道命名空间解析的前提以回答这些问题。

Is this legal? Is it obvious what's happening? You need to know the precendence of the namespace resolution to answer those questions.

这篇关于C ++命名空间,与Java包的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆