In fact, C also has the concept of this name space
It is useful to prevent naming conflicts, especially in large programs, to save energy and avoid errors. Can be all introduced, can introduce parts, but also can not be used. Doesn't matter.
using namespace Std; The name of the standard library is in Std.
1#include <iostream>2#include <string>3 using namespaceStd//Everything in the standard library is ready to use. The Way4 intMain ()5 {6cout <<"Please enter your name:"<<Endl;7 stringname;8 intAge ;9CIN >> Name >>Age ;Tencout << name <<"Hello, your age:"<< Age One<< Endl;//Endl The role of line-breaking, as well as the refresh buffer A //In C + +, the return 0 in the main function can be omitted, and the system will automatically add - return 0; -}
If only one part of the standard library is needed:
using std::cout; using std::cin; using Std::endl; using std::string;
The program actually requires only four standard libraries. :: Double colon is called the domain operator, a::b means B in the range of a.
Define your own namespaces
1#include <iostream>//not dot H2#include <string>3 using namespacestd;4 namespaceDashuai5 {6 stringName="Handsome";//need to add header file7 intAge = -;8 }9 namespaceLalalaTen { One Charname[ -]="la la la";//The same name is no problem, because it's a different namespace. A } - - //To use something under a namespace, you must first declare the using namespaceLalala; - using namespaceDashuai; - intMain () - { +cout <<"I was"<< Dashuai::name << Age <<Endl; -cout <<"Lalala"<< Lalala::name <<Endl; + return 0; A}
If you do not add namespaces, then will be error, there is ambiguity.
Note: Identifiers with different scopes, in principle, are local first, and the smaller the scope, the less the first consideration.
1cout <<"I was"<< Dashuai::name << Age <<Endl;2 3cout <<"Lalala"<< Lalala::name <<Endl;4 5 stringName ="AAAA";6 7cout << name << Endl;//this time, the aaaa is printed.
Here is the principle of local priority! This compiles without problems, because the program first finds the name inside the main function.
If it is a global variable, but also to follow the local priority principle, or no problem, print AAAA
If you want to print a global variable, use:: Name
1 stringName ="Global Variables";//2 intMain ()3 {4cout <<"I was"<< Dashuai::name << Age <<Endl;5cout <<"Lalala"<< Lalala::name <<Endl;6 stringName ="AAAA";7cout <<:: Name << Endl;//this time, we're printing global variables.8System"Pause");9 return 0;Ten}
Note: C + + puts variables that are not in the namespace into the anonymous namespace, using:: You can get them. The actual development of the time will not use so many namespaces, one is enough.
Use a local name of a namespace directly
using Dashuai::name; using dashuai::age;
Analogy using Std::cout;
C + + new namespaces namespace