C++ namespaces advice

前端 未结 9 1181
长发绾君心
长发绾君心 2020-11-28 21:48

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 l

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 22:20

    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.

    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.

    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:

    • they have methods
    • they can control access
    • they cannot be re-opened

    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.

提交回复
热议问题