1 namespaces resolve conflicts of global variables
1 main.h File2 #pragmaOnce3 //the name of the data namespace4 namespaceData5 {6 intnum = -;//External global variable conflict7 }8 9 Ten main.cpp One#include"Main.h" A#include <iostream> - using namespacestd; - the intnum =Ten; - - voidMain () - { +cout << Num <<Endl; -cout << data::num << Endl;//:: Domain modifiers must be used here to use the domain action + ACin.Get(); at}
2 namespaces are not private, all variables, functions are public and can be accessed
Using namespace data;//with namespaces, direct access as global variables
The inner layer covers the outer layers,
:: num accesses global variable directly, global variable does not exist is 0
The use of namespaces must be defined after
#include <iostream>using namespacestd;//namespaces do not have private, all variables, functions are public and can be accessed//using namespace data;//using namespaces, direct access as global variables//the inner layer covers the outer layers,//:: num accesses global variable directly, global variable does not exist is 0//the use of namespaces must be defined afternamespacedata{intnum; voidShow () {cout<< Num <<Endl; }}using namespaceData//using namespaces, direct access as global variables//the inner layer covers the outer layers,namespacedatax{intnum= -; namespaceRun {intnum =Ten; voidShow () {//:: num accesses global variable directly, global variable does not exist is 0cout << Datax::num <<Endl; } }}using namespacedatax;//the use of namespaces must be defined aftervoidMain () {datax::run::show (); Cin.Get();}voidmain1x () {Data::num=Ten; Show (); Cin.Get();}
3 Use of namespaces
1#include <iostream>2#include <cstdlib>3 using namespacestd;4 5 6 namespacestring17 {8 Charstr[Ten]{"Calc" };9 }Ten namespacestring2 One { A Charstr[Ten]{"Notepad" }; - } - //namespace extension, same name, same namespace the //Waterfall-style development - namespacestring2 - { - Charcmd[Ten]{"Notepad" }; + voidShow () - { +cout << str <<Endl; A } at } - - //namespaces, which can be nested indefinitely - namespaceRun - { - namespaceRunit in { - namespaceRunitout to { + intnum = -; - voidShow () the { *cout << Num <<Endl; $ }Panax Notoginseng } - } the + } A the + voidMain () - { $ //system (STRING2::STR); $ //string2::show ();//functions and variables for namespaces -Run::runit::runitout::num =199; - run::runit::runitout::show (); the - Wuyi theSystem"Pause"); -}
4 Anonymous namespaces
1#include <iostream>2 3 using namespacestd;4 5 6 //Anonymous namespaces equal to global variables7 namespace8 {9 intx =Ten;Ten } One A - voidMain () - { thex =3; -cout << x <<Endl; - - +Cin.Get(); - +}
C + + namespace namespace