Some knowledge points about namespaces

1. The namespace is open. You can add content to the namespace from multiple separate namespaces, such as:

namespace A
{
    void fun01();
}

namespace A
{
    void fun02();
}

There are two functions in namespace A. This feature is very useful, allowing functions in different files to be placed in the same namespace.

2. Variables with the same name:

namespace space
{
    int a = 111;
}

int a = 666;

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    int a = 444;
    debug "局部 " << a;
    debug "全局 " << ::a;
    debug "名称空间 " << space::a;
}

For the case where the namespace and the global variable have the same name, if the using display is used, the variable in the namespace will shield the global variable:

namespace space
{
    int a = 111;
}

int a = 666;

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    using space::a;
    ++a;
    debug "a = " << a;
}

This indicates that a is the a in space. Not for local variables:

3. The alias of the namespace, if the name of a namespace is very long, you can set an alias instead:

namespace IAnALongNamespace
{
    int a = 999;
}

#define debug qDebug()<<
int main(int argc, char *argv[])noexcept
{
    namespace space =  IAnALongNamespace;
    debug space::a;
}

4. Namespace and version management

Imagine the following application scenario: There is a function that needs to be updated to a new version, but the old version cannot be replaced in many places. Using namespaces allows the new and old versions to coexist and only need to make minimal changes without having to copy a lot:

namespace bigSpace
{
    inline namespace V2_0
    {
        void fun()
        {
            qDebug()<<"fun 2.0";
        }
    }

    namespace V1_0
    {
        void fun()
        {
            qDebug()<<"fun 1.0";
        }
    }
}

#define debug qDebug()<<
int main(int argc, char *argv[])noexcept
{
    bigSpace::fun();
    bigSpace::V1_0::fun();
}

The inline means the one in V2_0 that is used by default when the function with the same name is used. If the return value parameters are all the same, overloading cannot be used, and the use of namespaces is very simple.

5. Anonymous namespace, which can only be accessed by the current compilation unit:

namespace
{
    int a = 999;

    namespace
    {
        int b = 888;
    }
}

#define debug qDebug()<<
int main(int argc, char *argv[])noexcept
{
    debug a;
    debug b;
}

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/114125836