C + + namespaces

Source: Internet
Author: User

Reprint: Https://www.cnblogs.com/zhoug2020/p/5972439.html Why a namespace is required (problem raised)
命名空间是ANSIC++引入的可以由用户命名的作用域,用来处理程序中 常见的同名冲突。

3 levels of scope are defined in the C language, i.e., files (compilation units), functions, and compound statements. C + + introduces a class scope in which a class appears within a file. Variables of the same name can be defined in different scopes, and the system can distinguish them from each other.

1、全局变量的作用域是整个程序,在同一作用域中不应有两个或多个同名的实体(enuty),包括变量、函数和类等。

Example: If you define two classes in a file, you can have a function of the same name in these two classes. When referencing, for the sake of distinction, a class masterpiece should be added to the limit:
Class A//declare category A
{public:
void Funl ();//Declare FUNL function in Class A
Private
int i;};
void A::funl ()//define FUNL function in Class A
{............}

class B //声明B类{ public:    void funl(); //B类中也有funl函数    void fun2(); };void B::funl() //定义B类中的funl函数{ …………}

This will not be confusing.
In a file, you can define a global variable (variable), which is scoped to the entire program. If a variable a int a=3 is defined in file A;
A variable a int a=5 can be defined in file B again;
There is no problem when compiling file A and file B separately. However, if a program includes both file A and file B, an error is reported when the connection is made because there are two variables with the same name in the same program, which is considered a duplicate definition of the variable.
You can declare a variable of the same name in two files in the same program by using extern as the same variable. If you have the following declaration in file B:
Extem int A;
Indicates that variable A in file B is a variable that has already been defined in another file. Because of this declaration, after the program compiles and joins, the scope of variable A of file A is extended to file B. If you no longer assign a value to a in file B, the following statement in file B outputs the value of variable A in file a: cout<

Ii. What is a namespace (solution)

Namespaces: A memory area that is actually named by the program designer, which can be separated from other global entities by assigning some names to the domain and placing some global entities in each namespace, respectively.
such as: namespace NS1//specify named Middle NSL
{int A;
Double b; }
namespace is the keyword that must be written to define the namespace, NSL is the name of the user-specified namespace (which can be used with arbitrary legal identifiers, where NS1 is the abbreviation for namespace, meaning please), inside the curly braces is the declaration block, The entity in which it is declared is called a namespace member (namespace member). Now that the namespace members include variables A and B, note that A and B are still global variables and simply hide them in the specified namespace. If you want to use variables A and B in your program, you must add the namespace name and scope resolution "::", such as nsl::a,nsl::b. This usage is called namespace qualification (qualified), and these names (such as nsl::a) are called qualified names (qualified name). C + + is similar to the role of namespaces in the operating system of the directory and file relationships, due to a large number of files, inconvenience management, and easy to name, so people set up a number of subdirectories, the files are placed in different subdirectories, the files in different subdirectories can have the same name. The file path should be indicated when the file is called.
The role of namespaces is to create some separate scopes that separate some global entities from each other. In order to avoid the old point called Lee Sang, 3 people stood up to answer, this is the name conflict, because they can not tell what the teacher wants to call a Lee Sang, the same name can not distinguish each other. To avoid confusion with the same name, the school divided 3 students of the same name into 3 classes. In this way, when the small class is called Lee Sang, only one person will answer. In other words, the name is unique within the scope of the class (that is, the class scope). If the headmaster takes a name at the school and needs to look for the student within the whole campus, the scope problem needs to be considered. If the headmaster is called Lee Sang, there will be 3 people in the whole school who shout "to" because there are 3 students of the same name in the same scope. In order to differentiate the 3 students within the school, the headmaster must add the class number to the first name, such as the Lee Sang of the senior three class, or the Lee Sang of Class B, that is, the class name is limited. This will not create confusion.
You can set as many namespaces as you want, each namespace name represents a different namespace domain, and different namespaces cannot have the same name. In this way, you can put the entities in different libraries into different namespaces, or, in different namespaces, hide the different entities. The global variables we used in the past can be understood as global namespaces, independent of all well-known namespaces, and are not required to be declared with namespace, but are actually implicitly declared by the system and exist in each program.
When declaring a namespace, you can include not only variables in curly braces, but also the following types:
• Variables (can be initialized);
constant
• Number (can be defined or declared);
• Structural body;
Class
Template
• Namespaces (a namespace is defined in a namespace, which is a nested namespace).
For example
namespace NSL
{const int rate=0.08;//constant
Doublepay;//variables
Doubletax ()//function
{return a*rate;}
NAMESPACENS2//nested namespaces
{int age;}
}
If you want to output the data for a member in the namespace NSL, you can use the following method:
cout<

Iii. using namespaces to resolve name collisions (usage guide)

With this foundation in place, namespaces can be used to resolve name collisions. Now, the example 4 program is modified to make it work correctly.
Example 5 uses namespaces to resolve the problem of example 4 program name collisions.
Modify the two header files to place the classes declared in the header file in two different namespaces.
Header file 1 In example 8.5, file name Header1.h
using namespace Std;
#include
#include
namespace ns1//Declaration namespace NS1
{class Student//Declare Student classes within namespace NSL
{public:
Student (int n,string nam,int a)
{num=n;name=nam;age=a;}
void Get_data ();
Private
int num;
String name;
int age; };
void Student::get_data ()//define member functions
{cout<

Iv. methods for using namespace members

As you can see from the above introduction, when you reference a namespace member, you qualify the namespace member with the namespace name and scope resolution to distinguish between the same name identifiers in different namespaces. That
Namespace name:: namespace member name
This method is effective and ensures that the referenced entity has a unique name. However, if the namespace name is longer, especially if a namespace is nested, a long name is required for referencing an entity. It may be inconvenient to refer to a namespace member more than once in a program.
1. Using namespace aliases
You can use an alias (namespace alias) for a namespace instead of a longer namespace name. Such as
namespace television//declaration namespace, named television
{ ... }
You can replace it with a shorter, easy-to-remember alias. Such as:
namespace tv=television;//alias TV is equivalent to the original television
It can also be said that the alias TV points to the original television, in the originally appeared television position can be unconditionally used TV instead.
2. Using a using namespace member name
The namespace member name after the using must be a namespace-qualified name. For example:
Using Nsl::student;
The above statement declares that the member student in the namespace ns1 is used in this scope (the scope in which the using statement resides), and in this scope it is not necessary to use the namespace qualification if the namespace member is used. For example, after using the above using declaration, the Student that appears in subsequent programs is implicitly referring to Nsl::student.
The valid scope of a using declaration is from the start of the using statement to the scope at which the using is located. If you have the following statement after the using statement above:
Student studl (101, "Wang", 18);//The Student here is equivalent to Ns1::student
The above statement is equivalent to
Nsl::student studl (101, "Wang", 18);
And AS
Using Nsl::fun;//declare that the fun that follows is a fun part of the namespace NSL
cout<

Five, nameless namespaces

The above describes namespaces with names, and C + + also allows namespaces with no names, such as the following unnamed namespaces declared in file a:
namespace//namespace has no Name
{void fun ()//define namespace members
{cout<< "OK. "<

Vi. Standard Namespace Std

In order to resolve conflicts between identifiers in the C + + standard library and global identifiers in the program and identifiers in different libraries, the identifiers of different libraries should be defined (or declared) in different namespaces. All identifiers for the standard C + + library are defined in a namespace called STD, or the functions, classes, objects, and class templates in a standard header file (such as iostream) are defined in the namespace Std. STD is an abbreviation of standard, which indicates that this is the namespace for the content of the standard library, meaning please, do not rote.
In this way, when using the C + + standard library in your program, you need to use STD as a qualification. Such as
std::cout<< "OK. "<

Vii. using an early library of functions

C Language Program functions are basically implemented by the function, in the development process of C language to build a functional library, C + + from the C language inherited this valuable wealth. You can use the C-language function library in C + + programs.
If you want to use a function in a function library, you must include the relevant header file in the program file, including the declaration of the different functions in the different header files.
There are two ways of using these header files in C + +.
1, the traditional method of C language
The header file name includes a suffix. h, such as STDIO.H,MATH.H. Because the C language does not have a namespace, the header file is not stored in the namespace, so if a suffix is used in a C + + program file. h header file, you do not have to use a namespace. Just include the header file you used in the file. Such as
#include
2. A new method of using C + +
The C + + standard requires that the system provides header files that do not include suffixes. h, such as iostream, String. In order to indicate that there is a difference between the header file and the C language, the header file name used by C + + is the corresponding header file name in the C language (but does not include the suffix.) h) before adding a letter C. For example, the header file for input and output in the C language is named Stdio. h in C + +, the corresponding header file is named Cstdio. The header file in C language is math.h, and the corresponding header Wensch in C + + is named Cmath. The header file in the C language, string. h in C + +, the corresponding header file is named CString. Note in C + +, the header file Cstnng and the header file STRMG are not the same file. The former provides a declaration of a function (such as strcmp,ctrcpy) in the C language for string processing, which provides new functionality for string handling in C + +.
In addition, because these functions are declared in the namespace STD, the namespace STD is declared in the program. Such as:
#include
#include
using namespace Std;
Most of the C + + compiler systems currently in use retain the use of C and provide a new approach to D + +. The following two usages are equivalent and can be selected.
C New methods for traditional methods
#include #include
#include #include
#include #include
using namespace Std;
Traditional C methods can be used, but new methods of using C + + should be advocated.

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.