C + + namespaces

Source: Internet
Author: User

The purpose of using namespaces is to localize the names of identifiers to avoid naming conflicts. In C + +, variables, functions, and classes exist in large numbers. Without namespaces, the names of these variables, functions, and classes will all exist in the global namespace, causing many conflicts. For example, if we define a function toupper () in our own program, this overrides the ToUpper () function in the standard library, because both functions are in the global namespace. Naming conflicts can also occur in cases where a program uses two or more third-party libraries. At this point, it is quite possible that the name in one of the libraries is the same as the name in the other library, which is a conflict. This situation often occurs on the name of the class. For example, we define a stack class in our own program, and a library in our program may have a class with the same name, and the name conflicts.

The advent of the Namespace keyword is aimed at this problem. Because this mechanism is localized for the names declared therein, the same name can be used in different contexts without causing a name conflict. Perhaps the biggest beneficiaries of namespaces are the standard libraries in C + +. Before a namespace occurs, the entire C + + library is defined in the global namespace (which is, of course, the only namespace). With the introduction of namespaces, the C + + library is defined in its own namespace, called Std. This reduces the likelihood of name collisions. We can also create our own namespaces in our own programs so that we can localize names that we think might cause conflicts. This is especially important when we are creating classes or libraries of functions.

Namespace Basics

The namespace keyword allows us to separate the global namespace by creating a scope. Essentially, a namespace defines a scope. The basic form of defining the namespace is as follows:

namespace name {//declaration}

Anything defined in a namespace is confined to that namespace.

Here is an example of a namespace where a class that implements a simple decrement counter is localized. A counter class is defined in this namespace to implement the count, where Upperbound and lowerbound are used to represent the upper and lower bounds of the counter.

Demo namespaces

namespacecounternamespace{intUpperbound; intlowerbound; classCounter {intcount;  Public: Counter (intN) {if(N <=upperbound) {Count=N; } Else{Count=Upperbound; }      }    voidResetintN) {if(N <upperbound) {Count=N; }        }     intrun () {if(Count >lowerbound) {                returncount--; } Else {                returnlowerbound; }      }    };}

The Upperbound,lowerbound and class counter are all part of a namespace counternamespace definition scope.

An identifier declared in a namespace is a modifier that can be directly referenced and does not require any namespace. For example, in the Counternamesapce namespace, the run () function can refer to lowerbound directly in the statement:

if (Count > lowerbound) {return count--;}

However, since namespaces define a scope, we need to use the scope resolution operator to refer to the objects in the namespace outside of the namespace. For example, assigning a value of 10 to a upperbound outside the scope defined by the namespace Counternamespace must be written like this:

Ten , or an object that wants to declare a counter class outside the scope of the Counternamespace definition must be written like this: Counternamespace::counter obj;

In general, a member who wants to access the inside of a namespace outside the namespace needs to precede the member with the namespace and scope resolution operators.

The following program shows how to use the Counternamespace namespace:

#include<iostream>using namespacestd;namespacecounternamespace{intUpperbound; intlowerbound; classCounter {intcount;  Public: Counter (intN) {if(N <=upperbound) {Count=N; } Else{Count=Upperbound; }        }        voidResetintN) {if(N <upperbound) {Count=N; }        }        intrun () {if(Count >lowerbound) {                returncount--; }            Else                returnlowerbound; }    };}intMain () {Counternamespace::upperbound= -; Counternamespace::lowerbound=0; Counternamespace::counter Ob1 (Ten); inti;  Do{i=Ob1.run (); cout<< I <<" "; }  while(I >counternamespace::lowerbound); cout<<Endl; Counternamespace::counter Ob2 ( -); Do{i=Ob2.run (); cout<< I <<" "; }  while(I >counternamespace::lowerbound); cout<<Endl; Ob2.reset ( -);  Do{i=Ob2.run (); cout<< I <<" "; }  while(I >counternamespace::lowerbound); cout<<Endl; return 0;}

Note: The counter class and the references to Upperbound and Lowerbound are preceded by a counternamespace modifier. However, once an object of type counter is declared, there is no need to use this modifier on any member of the object. So Ob1.run () can be called directly. The namespaces can be parsed.

The same space names can be declared multiple times, and such declarations are complementary to each other. This allows namespaces to be split into several files or even different places in the same file. For example:

    1. namespace ns{int//... namespace ns{    int  J;}

      Where the namespace NS is divided into two parts, but the contents of the two parts are in the same namespace. i.e. NS. The last point: namespaces can be nested. This means that you can declare additional namespaces inside a namespace.

using Key Words

If you need to refer to a member of a namespace more than once in a program, it is cumbersome to use the scope resolver to specify the namespace each time, as we have previously said. To solve this problem, the Using keyword has been introduced. Using statements are typically used in two ways:

using namespace namespace name;

Using namespace name:: member;

The namespace name in the first form is the namespace we want to access. All members in the namespace are introduced into the current scope. That is, they are all part of the current namespace and are no longer required to use the scope qualifier. The second form simply makes the specified member in the specified namespace visible in the current scope. We use the preceding counternamespace for example, the following using statements and assignment statements are valid:

using // only the lowerbound is currently visible   The write is legal because the Lowerbound member is currently visible using//  All the members of the Counternamespace space are currently visible  to// It is legal to write, Because all the counternamespace members are now visible.

Here are the results of the changes we made to the previous program:

Use using

#include <iostream>using namespacestd;namespacecounternamespace{intUpperbound; intlowerbound; classCounter {intcount;  Public: Counter (intN) {if(N <upperbound) {Count=N; }            Else{Count=Upperbound; }        }         voidResetintN) {if(N <=upperbound) {Count=N; }        }         intrun () {if(Count >lowerbound) {                returncount--; }            Else            {                returnlowerbound; }        }    }; }intMain () {//It's just a upperbound in Counternamespace.    usingCounternamespace::upperbound; //access to Upperbound does not require the use of the range qualifier at this timeUpperbound = -; //however, when using lowerbound, it is still necessary to use the range qualifierCounternamespace::lowerbound =0; Counternamespace::counter Ob1 (Ten); inti;  Do{i=Ob1.run (); cout<< I <<" "; } while(I >counternamespace::lowerbound); cout<<Endl; //below we will use the entire Counternamespace namespace    using namespaceCounternamespace; Counter Ob2 ( -);  Do{i=Ob2.run (); cout<< I <<" "; } while(I >counternamespace::lowerbound); cout<<Endl; Ob2.reset ( -); Lowerbound= -;  Do{i=Ob2.run (); cout<< I <<" "; } while(I >lowerbound); return 0;}
The above program also demonstrates an important point: when we introduce a namespace using the using, if we have previously referenced other namespaces (or the same namespace), we will not overwrite the previous introduction, but rather supplement the previous introduction. That is, in the end, both the STD and Counternamespace namespaces in the above program become global spaces. There is a special namespace called an unnamed namespace. This namespace with no name allows us to create namespaces that are available in a file scope. Its general form is as follows:
namespace {  // content }

STD
name Space

Standard C + + defines its entire library in the Std namespace. This is why most of the programs in this book have the following code:

using namespace Std;

This is written in order to introduce the members of the Std namespace into the current namespace so that we can directly use the functions and classes in it, without having to write the STD every time::.

Of course, we can specify STD every time a member is used::, as long as we like. For example, we can display the following statement to specify cout:

Std::cout << "show using std:: to specify cout";

If our program uses only a small number of members in the Std namespace, or if the introduction of the Std namespace could lead to a namespace conflict, we would have no need to use the using namespace Std. However, if we are going to use the STD namespace members multiple times in the program, it would be much easier to introduce the members of the Std namespace into the current namespace by using namespace Std, rather than displaying the specified at the time of use alone.
Reprint Address: http://blog.renren.com/share/730973714/7874424429

C + + namespaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.