C + + anonymous namespace--anonymous space
Anonymous space, anonymous class, anonymous consortium, anonymous struct. Anonymous space
- #include <stdio. h>
- Namespace A {
- int ID = 1;
- }
- Namespace {
- int ID = one;
- }
- Namespace B {
- int ID = +;
- }
- int main(void){
- printf("id%d \ n", id);
- }
Output
- ID 11
The function of C is used here to reduce the disturbance of STD space. The output here is the contents of the anonymous space. Then it is similar to the following usage
- Namespace __unique_name_ {
- int ID;
- }
- using namespace __unique_name_;
If you modify the code as follows
- #include <stdio. h>
- Namespace A {
- int ID = 1;
- }
- Namespace {
- int ID = one;
- }
- Namespace B {
- int ID = +;
- }
- Namespace {
- int ID = a;
- }
- int main(void){
- printf("id%d \ n", id);
- }
compile the error, as follows
- T_anonymity_space.cpp:14:error:redefinition of ' int:: ID '
- T_anonymity_space.cpp:7: Error: ' int:: ID ' previously defined here
In a different file?
- File def.h
- Namespace {
- int ID = a;
- }
- #include <stdio. h>
- #include "Def.h"
- Namespace A {
- int ID = 1;
- }
- Namespace {
- int ID = one;
- }
- Namespace B {
- int ID = +;
- }
- int main(void){
- printf("id%d \ n", id);
- }
Compile error
- T_anonymity_space.cpp:7: Error:redefinition of ' int:: ID '
- Def.h:3: Error: ' int:: ID ' previously defined here
This shows that anonymous namespace is in a space. References to other spaces later usage
- #include <stdio. h>
- Namespace A {
- int ID = 1;
- }
- Namespace {
- int ID = one;
- int id =n;
- }
- Namespace B {
- int ID = +;
- }
- int main(void){
- printf("id%d \ n", id);
- using namespace A;
- printf("id%d-%d-%d \ n", A:: ID, :: ID, id);
- }
Output
- ID 11
- ID 1-11-12
Other spaces are referenced, and at this point if the use of anonymous space is in the same space, and the same name must be added:: To differentiate. I guess here, is the global variable in the default anonymous space? Judging from the phenomenon, probably is.
C + + anonymous namespace--anonymous space