* * Namespace: namespaces are services that address the naming conflicts of variables and functions in C + +.
* * The format basic format defined by namespace is:
namespace identifier
{
entities;
}
To give an example,
Namespace Exp
{
int A, B;
}
In order to use variables inside namespace outside of namespace, use:: operator, as follows
Exp::a
Exp::b
Using namespace can effectively avoid redefinition,
1#include <iostream>2 using namespacestd;3 4 namespace First5 {6 int var=5;7 }8 9 namespaceSecondTen { One Double var=3.1416; A } - - intMain () { thecout << First::var<<Endl; -cout << Second::var<<Endl; - return 0; -}
The result is:
5
3.1416
Two global variables are all names Var, but they are not in the same namespace so there is no conflict.
* * Using keyword
The keyword using can help introduce names from namespace to the current declaration area,
1#include <iostream>2 using namespacestd;3 4 namespace First5 {6 intx =5;7 inty =Ten;8 }9 Ten namespaceSecond One { A Doublex =3.1416; - Doubley =2.7183; - } the - intMain () { - usingfirst::x; - usingsecond::y; +cout << x <<Endl; -cout << y <<Endl; +cout << first::y <<Endl; Acout << second::x <<Endl; at return 0; - } - output is - 5 - 2.7183 - Ten in 3.1416 -As we specified the first X is First::x,y is SECOND.Y
The using can also be imported into the entire namespace,
1#include <iostream>2 using namespacestd;3 4 namespace First5 {6 intx =5;7 inty =Ten;8 }9 Ten namespaceSecond One { A Doublex =3.1416; - Doubley =2.7183; - } the - intMain () { - using namespaceFirst ; -cout << x <<Endl; +cout << y <<Endl; -cout << second::x <<Endl; +cout << second::y <<Endl; A return 0; at } - output is - 5 - Ten - 3.1416 - 2.7183
* * Namespace also supports nesting
1#include <iostream>2 3 namespace First4 {5 intA=Ten;6 intb= -;7 8 namespaceSecond9 { Ten DoubleA=1.02; One Doubleb=5.002; A voidhello (); - } - the voidSecond::hello () - { -Std::cout <<"Hello World"<<Std::endl; - } + } - + intMain () A { at using namespaceFirst ; - -std::cout<<second::a<<Std::endl; - Second::hello (); - } - output is in 1.02 -Hello World
Nesting namespace Second,seond in namespace first is not straightforward and requires first to be used indirectly.
* * Namespace can take aliases
It is a pleasant thing to use aliases for namespace with long names. However, as with using, it is best to avoid using namespace aliases in header files (f is more prone to conflict than first).
namespace F = First;
Use of C + + namespace