C ++ namespace, namespace
Overview
In C language, the program has only one global variable scope, and all global identifiers share the same scope. During Development by multiple people, identifier conflicts are easily caused. C ++ puts forward the namespace concept to solve this problem, and divides the global variable scope into different parts through the namespace. Different namespaces can have the same but no conflict.
Tips: identifier refers to constants, variables, statement labels, user-defined function names, user types, and so on.
Namespace Definition
Namespace name
{
// Custom identifier
}
Tips: 1. It is also called the default namespace in the global scope. All custom identifiers defined in the global scope belong to the default namespace.
2. namespaces can be nested and defined.
Example
namespace First{ int i = 0;}namespace Second{ int i = 1; int j = 2; namespace Internal { struct Stu { char name[30]; unsigned int number; }; }}
Namespace usage
After the namespace is defined, the namespace will be used. Because "global scope" is divided into multiple small global scopes through namespaces. Therefore, to use a namespace member, you must first determine which namespace the member belongs.
Direct use:
Namespace name: [namespace name:…] Member name;
Introduction:
1. Introduce the using namespace name [: namespace name…];
2. Introduce a single member in the namespace: using namespace name: [namespace name:…] Member name;
After the namespace member is introduced, you can directly use the member in the namespace. This is a problem. if the name of the introduced member is the same as the name of a local member, who will overwrite the Member or report an error?Both compiler Methods Adopt.
1. When a member used in the namespace is introduced, the partial member overwrites the member in the namespace.
2. When a single member in the namespace is introduced, the compiler reports an error.
Example:
# Include <stdio. h> namespace First {int I = 0;} namespace Second {int I = 1; int j = 2; namespace Internal {struct Stu {char name [30]; unsigned int number ;}}} int main (void) {using namespace First; // introduce all using Second: Internal: Stu; // introduce a single member printf ("I = % d \ n", I); // directly use printf ("I = % d \ n", Second :: i); // use Stu stu1 = {"Jude", 1} directly; // use printf ("stu1.name = % s \ n", stu1.name) directly after the import ); printf ("stu1.number = % d \ n", stu1.number ); ************** * **/int I; // No problem. using Second: j; int j; // return 0 ;}
Namespace alias
The alias of a variable is referenced last time. The namespace can also be an alias.
Define alias:
Namespace alias = namespace name