C++ namespace of C/C++

(1) Namespaces can be discontinuous and allow multiple levels of nesting

1. A namespace can be scattered and defined in multiple places in a file, and the separate namespaces complement each other .

Test 1

2. A namespace can be defined in multiple files. Namespaces can be discontinuous meaning that namespaces (class definitions and implementations) can be formed with separate interface files and implementation files. For example, the following MyClass class, although all in a namespace MyClassSpace, but this is still two parts, don't think that the variable b will be found in MyClassSpace in main.

Test 2

(2) Namespace aliases

Test 3

(3) using declarations and using compilation directives

1. Use the using statement

After a using declaration, only the declared member can be used.

Test 4

2. Use the using compilation directive

After using the using pragma, all members in the namespace are included in the current file.

Test 5

Using using namespace also has certain disadvantages, as follows

The difference between using global and local

The using statement can be referenced in a global way outside the function, such as using namespace std; which often appears; it can also appear in the function in a local way. The difference between the two is that the scope of the members after using is different.

(5) Anonymous command space

When a namespace is declared with an empty name , the namespace is an unnamed namespace . Anonymous space is a new alternative for C++ to use static definition scope for global functions or global variables of this compilation unit. Anonymous spaces can be nested like named namespaces. Since the anonymous namespace does not have the name of the namespace, the variable cannot be declared through extern in other compilation units, so the variable is naturally only visible in this compilation unit. Members of an anonymous namespace can be referenced via ::member_name.

Using anonymous space has at least two advantages over using static:

1) For a set of multiple identifier functions, only one anonymous space needs to be used to declare, and there is no need to enter static multiple times.

2) Can be nested. This allows multiple identifiers with the same name to be used in different namespaces.

In the C++ standard, it is also recommended to use anonymous namespaces to define global variables within the compilation unit instead of static. The static keyword is considered a deprecated feature here.

(6) std namespace

Standard C++ defines its entire library in the std namespace.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325379630&siteId=291194637