C ++命名空间通知 [英] C++ namespaces advice

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

问题描述

我只是教自己的C ++命名空间(来自C#背景),我真的开始认为,即使所有的事情,C ++比大多数其他语言,嵌套命名空间不是其中之一!

I'm just teaching myself C++ namespaces (coming from a C# background) and I'm really starting to think that even with all the things that C++ does better than most other languages, nested namespaces isn't one of them!

我想是为了声明一些嵌套的命名空间,我必须做以下事情:

Am I right in thinking that in order to declare some nested namespaces I have to do the following:

namespace tier1
{
    namespace tier2
    {
        namespace tier3
        {
            /* then start your normal code nesting */
        }
    }
}

namespace tier1::tier2::tier3
{
}

àla C#?

当我需要转发时, declare:

This becomes even more demented when I need to forward declare:

namespace tier1
{
    namespace tier2
    {
        namespace forward_declared_namespace
        {
            myType myVar; // forward declare
        }
        namespace tier3
        {
            /* then start your normal code nesting */
            class myClass
            {
                forward_declared_namespace::myType myMember;
            }
        }
    }
}



我开发的典型系统包括:

Bearing in mind that a typical system that I develop consists of:

MyCompany::MySolution::MyProject::System::[PossibleSections]::Type

这是为什么你不倾向于在C ++示例中看到很多使用命名空间?或通常只有一个(不是嵌套)命名空间?

Is this why you don't tend to see much use of namespaces in C++ examples? Or usually only single (not nested) namespaces?

UPDATE

感兴趣的,这是我结束了解决这个问题。

For anyone interested, this is how I ended up tackling this issue.

推荐答案

C ++命名空间并不是一个设计机制 - 它们只是为了防止名称冲突。你真的不想或者需要在99.99%的情况下使用嵌套的命名空间。

C++ namespaces were not intended to be a design mechanism - they are there simply to prevent name clashes. You really don't want or need to use nested namespaces in 99.99% of situations.

在C ++中正确使用命名空间的一个很好的例子是C ++标准库。这个相当大的库中的所有内容都放置在名为 std 的单一命名空间中 - 没有尝试或需要将库拆分为(例如)I / O子命名空间,命名空间,容器子命名空间等。

A good example of the correct use of namespaces in C++ is the C++ Standard Library. Everything in this quite large library is placed in a single namespace called std - there is no attempt or need to break the library up into (for example) an I/O sub-namespace, a math sub-namespace, a container sub-namespace etc.

在C ++中建模的基本工具是类(在某种程度上是模板),而不是命名空间。如果你觉得需要嵌套,你应该考虑使用嵌套类,它比命名空间有以下优点:

The basic tool for modelling in C++ is the class (and to some extent the template), not the namespace. If you feel the need for nesting, you should consider using nested classes, which have the following advantages over namespaces:


  • li>
  • 他们可以控制访问权限

  • 无法重新打开

考虑过这些,如果你仍然希望通过所有方式使用嵌套的命名空间,这样做是没有什么技术上的错误。

Having considered these, if you still wish to use nested namespaces by all means do so - there is nothing technically wrong with using them in this way.

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

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