[c++] namespace
1. Definition of namespace
2. Using command
3. The relationship between classes and namespaces
refer to:
"C++ from entry to proficient" People's Posts and Telecommunications Publishing House
1. Definition of namespace
Namespace is the namespace. A file is a physical way of dividing a program into chunks, while a namespace is a logical way of dividing a program into chunks.
C++ uses a single global variable namespace. In this single space, if there are two variables or functions with the same name, a conflict will occur. Namespace is a mechanism introduced to solve the naming conflict of variables and functions in C++. The main idea is to define variables in namespaces with different names.
For example, there are Class 1 of Senior 1 in No. 1, and Class 1 of Senior 1 in No. 2, but because they belong to different schools, we can correctly distinguish these two classes.
Benefits of namespaces:
1. Avoid naming conflicts
2. Simplify access to class members
Programming example: call the print() function in two different namespaces respectively
//namespace.cpp #include<iostream> using namespace std; namespace name_1 //namespace 1 { void print() { cout<<"Call print() in name_1 space"<<endl; } } namespace name_2 //namespace 1 { void print() { cout<<"Call print() in name_2 space"<<endl; } } intmain() { name_1::print(); //Call print() in the name_1 space, "::" is the scope resolution operator name_2::print(); //call print() in name_2 space return 0; }
operation result:
Analysis: Use the scope resolution operator "::" to call the function print() in the namespace.
Name of the namespace:
To simplify names, namespaces can be aliased with abbreviations, etc.
Namespace IBM=International_Business_Machine_Corporation
Then you can IBM::print();
2. using directive
For example the most commonly used: using namespace std;
Note : The scope of the using directive . usingnamespace is only valid within the statement block in which it is declared (a statement block refers to a group of instructions within a pair of curly braces {}).
intmain() { { //block 1 using namespace name_1; name_1::print(); //call print() in name_1 space } { //block 2 using namespace name_2; name_2::print(); //call print() in name_2 space } return 0; }
operation result:
3. The relationship between classes and namespaces
Namespaces are a way of organizing classes. If a class is compared to a file in a computer, a namespace is like a folder, which implements the classification management of classes, and adds structure and hierarchical organization to the class library.
------------------------------------------- END -------------------------------------