Acquaintance learning C ++ namespace

Disclaimer :
            I am self-learning C ++, there is no basic computer, it is inevitable there will be mistakes in understanding the process of learning, irrelevant phenomenon, there may even be laughable. If you have C ++ Daniel to be able to sweep my blog, sincerely I hope that Daniel can give criticism and correction! Greatful!
            The learning process is divided into first met, entry, advanced three stages.
            Because there is no knowledge of C ++, such a study may also be set beneath accuracy. Brothers hope more guidance. Thank you!



Contents:
science: the identifier, the scope of
the origin of the space command 1. What is emerging and global namespace namespace and
invoke the command space 2.
3. Define, add a namespace and a member of
4 nested namespace
5. Unnamed namespace
review


science:
in learning namespace ah, there is such a concept must first figure out. Otherwise, you will learn monk puzzled. This is the identifier.
Identifier:
 Identifier is a sequence of characters used to represent one of the following:
    
    Object variable name or
    class, structure, or union name of the
    enumeration type name
    members of a class, structure, union, or enumeration
    function or class member functions
    typedef name
    Label name
    macro name
    macro parameter
    
  said simply, the identifier is the name refers to objects, variables, classes, structures, etc.

make up the rules for identifiers: the first character must be a letter or underscore, in addition to the first character by character, numbers, underscores

scope:

    in general, a program code using an identifier is has a restricted range, and this identifier in the code range which can be used is the scope of the identifier.    
    For objects (the other is the same), such as within the main function, the scope object to it recently in a pair of curly braces. Scope global target for the whole file after the statement (within a single file, multiple files is not involved in the project).

    We take a variable to give an example:
Halberd: ~ # CAT scope1.cpp

    #include <iostream>
    using std::cout;
    using std::endl;
    int a=2;

    class test {
    public:
        test() {
        cout << \"Testing varialbe \\\"a\\\" is used out of main()!\" << endl;
        cout << \"Testing variable \\\"a\\\" is :\" << a << endl;
        test1 ();
        }
        static void test1() {
            cout << \"Testing varialbe \\\"b\\\" cout not be used out of main()!! \" << endl;
            // cout << \ "Testing variable \\\" b \\\ "is \" << b << endl; // The key is this line! It has not been the case with the comments under Note annotated case
        }
    };
    static test test;
        
    int main ()
    {
      int b=3;
      cout << \"variable \\\"a\\\" be used in main is :\" << a << endl;
      cout << \"variable \\\"b\\\" be used in main is :\" << b << endl;
      return 0;
    }
halberd:~ # g++ scope1.cpp -o scope1
halberd:~ # ./scope1
Testing varialbe "a" is used out of main()!
Testing variable "a" is :2
Testing varialbe "b" cout not be used out of main()!! 
variable "a" be used in main is :2
variable "b" be used in main is :3

 


outside a defined {}, b is defined in the {}.
We saw above normal program code is compiled, executed properly, a different can call} {, b can be invoked within the {}, but if you can call it different within {}?
Look at the situation after the next uncommented lines:

Halberd: ~ # CAT scope1.cpp

   #include <iostream>
    using std::cout;
    using std::endl;
    int a=2;

    class test {
    public:
        test() {
        cout << \"Testing varialbe \\\"a\\\" is used out of main()!\" << endl;
        cout << \"Testing variable \\\"a\\\" is :\" << a << endl;
        test1 ();
        }
        static void test1() {
            cout << \"Testing varialbe \\\"b\\\" cout not be used out of main()!! \" << endl;
            cout << \ "Testing variable \\\" b \\\ "is \" << b << endl; // The key is this line! It has not been the case with the comments under Note annotated case
        }
    };
    static test test;
        
    int main ()
    {
      int b=3;
      cout << \"variable \\\"a\\\" be used in main is :\" << a << endl;
      cout << \"variable \\\"b\\\" be used in main is :\" << b << endl;
      return 0;
    }
halberd:~ # g++ scope1.cpp -o scope1
scope1.cpp: In static member function ‘static void test::test1()’:
scope1.cpp:15:49: error: ‘b’ was not declared in this scope
         cout << "Testing variable \"b\" is " << b << endl;  

 


Here we see an error at compile time. Tip is not declared in the scope in b. From here we show that, b can only be used within the {} is declared, out of this part of the code area, the program can not be identified.

The example above scope identifiers a whole file, or the main function can be used either in the main outside, this code in the file identifier is not a limitation of the use, that is to say the identifier of a scope is the entire file.
And b is in the usable range {} inside the main function, that is to say b scope {} in the main function. When calling outside the main function, we found it impossible to compile, suggesting: error: 'b' was not declared in this scope ( 'b' was not declared in this scope). That was what scope does not declare it? Is test1 () {} braces inside the.
So after our test, if you can say this:

the scope of the maximum range of a single file is the entire code files, the minimum range is within the scope of the code identifier where the braces,

why the special instructions within a single document? Because as we learn more and more, that time will extend the scope of the situation encountered, such as an identifier is referenced by extern to another file, so this scope identifier would have been extended. Getting so after we come to learn it. Here only you need to realize that there are other cases on it.

1. The origin of the name space, what is the namespace and global namespace

   In recognition of what is before namespace, we start to understand why there is this thing namespace.
   Before understanding, we think about, we go to school, is not often encounter the same sex have the same name as the students ah? I believe many people have this experience. Then the next we assume, in the absence of sub-professional, no sub-class, opened a school assembly, the General Assembly president passionate remarks, to call a A student came to power, as to why you want to be called on stage, called stage why we do not consider just imagine this scene, and this school has 10 students called A, the principal, the audience stood up and hula 10 students, the principal is not Mong out ah? Haha
   , however, the principal learned that he wanted to call the students of this college which is what any professional classes, the principal to find this person is not the time there would not be the case in accordance with the above information? The president said the college students A's, professional, class information together out, avoids the problem of name conflicts.

   In C ++ development process, will encounter a similar situation, the same identifier in the same scope statement many times, when compiling the program there will be conflict, the compiler does not know which identifier should be used, this conflict, called in C ++ is called Namespace Pollution. That in order to avoid or to solve this problem, we need to add some additional information about these identifiers: "college", "professional" and "class", additional information that corresponds to our code files, it is a namespace.
   
   Now we know that the namespace is how come, then how do we understand this namespace? I think we should be understood from two perspectives, one is composed of a role.
   
        The same metaphor, "class" is a namespace, what the class has it? The class is not all people ah? Professors, teaching assistants there, there are male students, female students and so on. Then we can interpret it this way: From the point of view in terms of the composition of the namespace, a namespace is a collection, collection of what it?
Namespace declaration is part of its set identifier.
       So how should we understand from the perspective of the role of the namespace it?
       We know, namespace identifier statement is used to avoid the situation of conflict. That namespace is itself what role it appear? In fact, we can understand, namespace is a scope. C ++ program codes, by a different scope compositions have different identifiers in a single scope, the presence of the same identifier have different scopes, when we want to specify an identifier, which is one way using namespace. That, in itself a namespace scope.

   In summary, we know, the namespace itself is a scope and a statement by the identifier components.
   
   Then how do we understand the global name space?
   "C ++ Primer", wrote:
   Names defined AT, Ltd. Free Join scopenames declared Outside the any class, function, or namespaceare defined Inside at The, Ltd. Free Join namespace at The, Ltd. Free Join namespace IS implicitly declared and EXISTS in Every Program Each File that Defines Entities AT, Ltd. Free Join scope ADDS.. those names to the global namespace
   as I understand it, the global namespace, is implicitly defined namespace, there is no clear name, where you can share the entire program (functions, classes, namespaces other than) a statement codes are declared in the global namespace.
   Use global namespace identifiers, requires the use of a scope identifier "::"
   

2. The call command space

   Oh, we do understand what is namespace now to learn how to use it. We want to learn as well as use, it does not become a learned paper yet ...... hey
   namespace There are three usage (with std for example):

Called advantage Shortcoming recommend
using namespace std;    Easy to use, no need to repeat specified, do not need to specify the namespace to use next time Throughout all of the namespace file open, easily lead to conflict identifier no
using std:cout;  Precise positioning, without having to repeatedly specify, do not need to specify the namespace next time you use the identifier is not prone to conflict. unknown Yes
std::cout;   Precise positioning, Next time you use need to specify the namespace but tedious writing no

   
Instructions on calling namespace keyword, symbol:
   using: indicator, when using as an indicator to use, must be followed by namespace keyword, if not behind with the declared namespace error. Of course, using other features, such as re-declare the base class member, and then study this behind it. All of a sudden not eat through so many things.
   ::: scope qualifier, its role is to explain "::" scope of the latter with the identifier is located, it is the same namespace appear together for the identifier to avoid problems of conflict. Such as: std :: cout, cout description identifier is the scope of std cout, the program finds the "::" will be the scope of the pre-qualifier declaration code to find the identifier to determine the identifier function.
          If the qualifier in front of what did not it? That program will find this identifier is defined, the statement from the global scope. (When will it be used? Boring ah ~ do not know much, can not think of a scene - big hope God will give an example, to save a life than build a seven Budo ah ~ teach people to eat better than a roll of one thousand Bowl , meritorious !! thank old worn Tip: when will use static member functions, etc. and when learned later study classes and functions)

3. Define, add a namespace and members


   Toss a few days, and finally be namespace is what, let's define the namespace to learn it ~ ~ it exciting moment came
   
   grammatical structure 3.1 Definitions namespace
   

       namespace namespace_name {
       ............ // Statement section
       }

      Before specific written, we must first understand the definition of the namespace What are the limits:
      A) Because the namespace is just a manifestation of the scope, and therefore need to comply with the rules of the domain naming identifiers role: the role of domain names in the scope can only be unique, otherwise there will be conflict. Namespace, too, in a namespace, the name must be unique.
      b) namespaces or define other scopes in the global scope, but not in function, class structure defined inside
      namespace scope can not end with a semicolon c)
      
      that namespace what allows us to define it? Hey, as long as any statement can appear in global scope can be defined in a namespace, such as classes, variables and initialization, and function definitions, templates and other namespaces (note not? Namespace can have namespaces it, that namespace can actually be nested, it will learn more about later.)
      
      come on, let's write a simple gray often namespace, to enjoy the fun of a write namespace, hey.
      code show as below:

    #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    namespace halberd_ns {
            int a = 1;
    }

    int a = 2;

    int main ()
    {
    cout << \"This variable is from namespace halberd_ns: a=\"<<halberd_ns::a<<endl;
    cout <<\"This variable is from global namesapce :: a=\"<<a<<endl;
    return 0;
    }

 

Compile:
Halberd: / Home / C ++ / G ++ ./namespace_.cpp Codes # -o namespace_ 
execution:
Halberd: / Home / C ++ / Codes # ./namespace_ 
This namespace variable from halberd_ns IS: A = 1 // From here we see to define and initialize a namespace variable success, and successfully calling namespace variable outside the namespace
This variable is from global namesapce :: a = 2

Haha, succeeded.

3.2 merge namespace (2014-06-30 Supplementary)
In fact, C ++ namespace, you can write separately. Can be part of different functions are declared in the same file can be assigned to several file declarations. Let's do an experiment:
   in the previous section, I define a namespace:. Halberd_ns Below, we take this tool is based on the experiment. First restatement of the same name within the file namespace:
Halberd: / Home / C ++ / Codes # cp namespace_.cpp ./namespace_1.cpp
Halberd: / Home / C ++ / Codes # vi namespace_.cpp
Halberd: / Home / C ++ / Codes # cat namespace_1.cpp

    #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    namespace halberd_ns {
            int a = 1;
    }

    int a = 2;

    namespace halberd_ns { // new namespace declaration - to see what role 
            int b = 3 ;
    }

    int main ()
    {
    cout << \"This variable is from namespace halberd_ns: a=\"<<halberd_ns::a<<endl;
    cout <<\"This variable is from global namesapce : a=\"<<a<<endl;
    cout <<\"This variable is used to test namespace consolidation: b=\" <<halberd_ns::b<<endl; //验证我们的猜想
    return 0;
    }

 

See section modified above, is a new declaration of a namespace halberd_ns, then add a line to verify whether the two namespaces into force at the same time.
Look Results:
Halberd: / Home / C ++ / ++ G ./namespace_1.cpp Codes # -o namespace_1
Halberd: / Home / C ++ / # ./namespace_1 Codes 
This variable from namespace halberd_ns IS: A. 1 =
This variable IS from Global namesapce : a = 2
This variable Used to the Test iS namespace Consolidation: b = 3

we see that:
first, the original namespace is not covered by the original statement also effective.
Second, existing namespace declaration puts the contents of two namespaces combined, at the same time to take effect, which is equivalent to the combined namespace.

Here we do an experiment, we declare the same namespaces in different files, to see what effect it would be:
alberd: / Home / C ++ / Codes # vi attach_namespace.cpp
Halberd: / Home / C ++ / CAT attach_namespace Codes # .cpp

    #include <iostream>
    namespace halberd_ns{
            int c=4;
    }

halberd:/home/C++/codes # vi namespace_1.cpp
halberd:/home/C++/codes # cat namespace_1.cpp

    #include <iostream>
    #include \"attach_namespace.cpp\"
    using std::cout;
    using std::cin;
    using std::endl;

    namespace halberd_ns {
            int a = 1;
    }

    int a = 2;

    namespace halberd_ns {
            int b = 3;
    }

    int main ()
    {
    cout << \"This variable is from namespace halberd_ns: a=\"<<halberd_ns::a<<endl;
    cout <<\"This variable is from global namesapce : a=\"<<a<<endl;
    cout <<\"This variable is used to test namespace consolidation: b=\" <<halberd_ns::b<<endl;
    cout <<\"This variable is used to test outer file\'s namespace consolidattion: c=\" <<halberd_ns::c<<endl;
    return 0;
    }

 

Halberd: / Home / C ++ / ++ G ./namespace_1.cpp Codes # -o namespace_1
Halberd: / Home / C ++ / # ./namespace_1 Codes
This variable from namespace halberd_ns IS: A. 1 =
This variable from Global namesapce IS: A = 2
Used to the test iS variable This namespace Consolidation: b = 3
This variable Used to the test iS File's Outer namespace consolidattion: c = 4

from the above experiments, we see that the namespace halberd_ns, respectively, in a statement attach_namespace.cpp once, and declared twice namespace_1.cpp. Attach_namespace.cpp file is referenced to namespace_1.cpp, the namespace declarations are also cited over. And namespace declaration can be used normally.
So, we can say this:

1) namespace declarations, definitions may be discontinuous, a namespace can be distributed to multiple files, or separately declared or defined in different parts of the same file.
2) of the same name namespace (non-repeating) fame, definitions, can be accumulated, combined, in the outside world, as if it were only through a statement the same.

3.3 Adding a namespace member (to be supplemented)
       (3.2 feel content with some duplication, but is really a new thing. Associated with the class, and discuss old wearing a long time, did not understand. First put it has been waiting completion of the class again supplement this one)

4. nested namespace (2014-07-01 supplement)

     The so-called nested namespace, in fact, in another namespace scope definition of a namespace. Format similar to the following:

     namespace halberd_ns {
                             namespace halberd_ns1{
                            //definitions
                            ……
}
}

 

   Come on, we do an experiment:

Click (here) folded or unfolded

    #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    namespace halberd_ns {
            int a = 1;
            namespace halberd_ns_nested{
                    int b=2;
                                    }
    }


    int main ()
    {
    cout << \"This variable is from namespace halberd_ns: a=\"<<halberd_ns::a<<endl;
    cout <<\"This variable is from nested namesapce halberd_ns_nested:: b=\"<<halberd_ns::halberd_ns_nested::b<<endl;
    return 0;
    }

 

Compile:
Linux-emf1: / Home / C ++ / ++ G ./namespace_nested.cpp Codes # -o namespace_nested
executed to verify:
Linux-emf1: / Home / C ++ / # ./namespace_nested Codes 
This variable from namespace halberd_ns IS: A. 1 =
This variable is from nested namesapce halberd_ns_nested :: b = 2

Hey, it really has succeeded. How, we learn, it is not difficult. Although there are not met, and can not understand. However, we have been in progress yet. Right. As long as the forward, success will be away from getting closer.

 

The unnamed space (2014-07-01 supplement)

     Unnamed namespace, What do you mean, I do not say it, that is not the name thing.
     Defined format is as follows:

     namespace {
    // definitions
    ……
     }

 

     Earlier we had understanding of the global namespace, and the impression is not, not, to look at the top of this page. This global namespace similarities. You know what is not? Yes, that is no name. So what is the difference between them? Clarify this distinction, the characteristics of this we did not name the namespace will understand:

Compared Global namespace Unnamed namespaces
Whether to allow nesting no It is allowed to be nested within other namespaces
Use of Global, members can be referenced in any project file Local, local effects can only use a domain in a file, the file can not cross-use
Reference member ' Use scope qualifier "::" Member name directly, you can not use a scope qualifier "::"
Defined way Occult definitions (automatically defined, each project has its own a global default namespace) Explicitly defined

Unnamed Namespace Other features:
1) variable unnamed namespace definition is created when the program began, there has been a release at the end of the program
2) If the outermost layer of the definition of an unnamed namespace name can not be a member of the the name of the global scope is not the same, why? Will clash with members of the global namespace chant

review:
We all learn namespace for what things?
1. What is the identifier and the scope of
the origin of the name space 2. 
3. What is the name space (acting from two aspects to consider and composition)
call 4. namespace
definition of namespace 5.
6. namespace merge
7. add namespace member (to be added)
8. unnamed space
9. nested namespace

Guess you like

Origin www.cnblogs.com/halberd-lee/p/11068718.html