What is a namespace ? Why write using namespace std; this sentence?
This is a newly introduced mechanism in C++, mainly to solve the problem of naming conflicts between multiple modules, just like two people with the same name in real life. C++ puts the same names in different spaces to prevent name conflicts.
For example, the objects provided by the standard C++ library are stored in the standard namespace std, such as cin, cout, and endl, so we will see the sentence using namespace std; in C++ programs, such as the program:
#include<iostream>usingnamespacestd;intmain(){cout<<Nicetomeetyou!<<endl;return0;}
If the program uses cout and endl, it must be informed in advance to use the std namespace. In addition, there are two other ways of writing.
The second type: Use domain qualifier:: to specify one by one. The code just now can also be written as:
#include<iostream>intmain(){std::cout<<Nicetomeetyou!<<std::endl;return0;}
Did you see that? cout and endl are respectively specified with std::, indicating that they come from std.
The third method: Use using and domain qualifiers to specify which names to use, such as code:
#include<iostream>usingstd::cout;usingstd::endl;intmain(){cout<<Nicetomeetyou!<<endl;return0;}
Did you see that? You can also use using to declare the specific name first.
You can use any of the above three methods. For the sake of unification and convenience in the future, we will adopt the first writing method in our tutorials.
It is worth mentioning that in fact, the early C++ standard did not have the concept of namespace, and the header file included was the same as C, with the .h suffix. It's just that when using a header file without .h to include in the new standard, the namespace must be declared, and the included header file comes first, and the namespace used is declared last.