VC ++ namespace

Source: Internet
Author: User
Tags cmath
VC ++ namespace

Basic Requirements

* Knowledge: the role and definition of a namespace; and how to use a namespace.
* Understanding: Using early function libraries
Key points and difficulties
◆ The role and definition of a namespace; how to use a namespace.

When studying the previous chapters of this book, the reader has repeatedly seen the following statements used in the program:

Using namespace STD;

The namespace STD is used. This document will introduce it in detail.

I. Why do I need a namespace)

The namespace is a scope introduced by ansic ++ that can be named by users. It is used to handle common conflicts of the same name in programs.

The C language defines three levels of scopes: files (compilation units), functions, and composite statements. C ++ introduces the class scope, which appears in the file. Variables with the same name can be defined in different scopes. They are different from each other and can be differentiated by the system.


1. The scope of global variables is the whole program. In the same scope, there should be no two or more entities with the same name (enuty), including variables, functions, and classes.

Example:If two classes are defined in the file, the two classes can have functions with the same name. When referencing, the class name should be added as a limitation for the sake of difference:
Class// Declare Class
{ Public:
Void funl ();//Declare the funl function in Class
PRIVATE:
Int I ;};
Void A: funl ()// Define the funl function in Class
{............}

Class B// Declare Class B
{ Public:
Void funl ();// There are also funl functions in Class B
Void fun2 ();};
Void B: funl ()// Define the funl function in Class B
{............}
This will not cause confusion.

You can define a global variable in the file. Its scope is the entire program. If a variable A int A = 3 is defined in file;
In File B, you can define another variable A int A = 5;
No problem occurs when compiling files A and B respectively. However, if a program contains files a and B, an error is reported during connection because there are two variables with the same name in the same program, it is considered to be a repeated definition of variables.
You can use extern to declare that the variables with the same name in two files in the same program are the same variable. If file B contains the following statement:
Extem int;
Variable A in file B is a variable defined in other files. With this declaration, after the program is compiled and connected, the scope of variable A of file a is extended to file B. If a is no longer assigned to file B, the following statement is used in file B to output the value of variable A in file a: cout <;// Obtain the value of a as 3.
2. A name conflict occurs in the program.
In simple programming, as long as people pay attention to it, they can try to avoid errors. However, a large application software is often completed by several people rather than independently. Different people complete different parts separately, finally, it is combined into a complete program. If different people define classes and put them in different header files, use the # include command line to include these classes when the main files (files containing the main function) need to use these classes. Because the header files are designed by different people, it is possible that different header files use the same name to name the defined classes or functions.

Example 4 Name Conflict

Programmer A defines the class student and function fun in the header file headerl. h.

// Header file header1 in Example 4 (header file 1, without its file name being cc8-4-h1.h)
# Include <string>
# Include <cmath>
Using namespace STD;
Class student// Declare the student class
{ Public:
Student (int n, string Nam, int)
{ Num = N; name = Nam; age = ;}
Void get_data ();
PRIVATE:
Int num;
String name;
Int age ;};
Void Student: get_data ()// Member function definition
{Cout <num <"" <name <"" <age <Endl ;}
Double fun (double A, double B)// Define global functions (external functions)
{Return SQRT (a + B );}

The file where the main function is located contains the header file headerl. h:
# Include <iostream>
Using namespace STD;
# Include "header1.h"// Note that double quotation marks are used, because files are generally placed in the user directory.
Int main ()
{Student stud1 (101, "Wang", 18 );// Define the Class Object studl
Stud1.get _ data ();
Cout <fun (5, 3) <Endl;
Return 0 ;}

The program runs normally and the output is
101 Wang 18th
2.82843

If programmer B writes the header file header2.h, in addition to defining other classes, it also defines the class student and function fun, but its content and header file headerl. student in H is different from function fun.

// Header file header2 in Example 4
# Include <string>
# Include <cmath>
Using namespace STD;
Class student// Declare the student class
{Public:
Student (int n, string Nam, char S)// The parameter is different from the student in headerl.
{Num = N; name = Nam; Sex = s ;}
Void get_data ();
PRIVATE:
Int num;
String name;
Char sex ;}; // Different from headerl

Void Student: get_data ()// Member function definition
{Cout <num <"" <name <"" <sex <Endl ;}

Double fun (double A, double B)// Define global functions
{Return SQRT (a-B );}// The returned value is different from the fun function in headerl.
// Other content may exist in header file 2.

If the main programmer needs to use headerl in his program. student and function fun in H, so the program contains the header file headerl. h. At the same time, some content in the header file header2.h is used (however, header2.h contains headerl. the student class and the fun function in h have the same name and different classes and functions are not informed, because a header file usually contains many different information, users often only care about what they need, but do not pay attention to other content), so the program contains the header file header2.h. If the main file (the file containing the main function) is as follows:

# Include <iostream>
Using namespace STD;
# Include "header1.h"// Contains the header file L
# Include "header2.h"// Contains header file 2
Int main ()
{Student stud1 (101, "Wang", 18 );
Stud1.get _ data ();
Cout <fun (5, 3) <Endl;
Return 0 ;}

At this time, the program compilation will fail. After pre-compilation, the header file replaces the corresponding # include command line, so two student classes and two fun functions appear in the same program file, it is clearly a duplicate definition. This is a name conflict, that is, there are two or more entities with the same name in the same scope.

3. global namespace pollution ).
Some libraries (including libraries provided by C ++ compiling systems, libraries provided by software developers, or self-developed libraries) are often referenced in programs ), to this end, you need to include the relevant header file. If these libraries contain entities with the same name as the program's global entity, or different libraries have the same entity name, a name conflict occurs during compilation.

To avoid such problems, people have proposed many methods, such as writing Entity Names (containing dozens or dozens of letters and characters ); special names include special characters. Internal global identifiers provided by the compilation system use underscores as prefixes, such as _ complex (), to avoid the same name as the entity named by the user; the Entity names provided by software developers use specific characters as the prefix. However, this effect is not ideal, and it increases the difficulty of reading the program and reduces readability.

C language and the early C ++ language did not provide an effective mechanism to solve this problem, and they did not enable database providers to build their own namespaces. We hope that the ansi c ++ standard can solve this problem by providing a mechanism and a tool, the GLobal IDEntifier named by the Database Designer can be different from the global entity name of the program and the global identifier of other databases.

Ii. What is a namespace (solution)

Namespace:It is actually a memory area named by the program designer. The program designer can specify some namespace fields as needed and put some global entities in each namespace, separated from other global entities.

For example:Namespace NS1// Specify the name center NSL
{Int;
Double B ;}

Namespace is required to define the namespaceKeywordsNSL is specified by the user.Namespace name(You can use any legal identifier. Here NS1 is used because ns is short for namespace and has a clear meaning.) The block is declared in curly brackets, in which the declared entity is calledNamespace member ).Currently, namespace members include variables A and B. Note that A and B are still global variables and only hide them in the specified namespace. If you want to use variables A and B in the program, you must add the namespace name and scope identifier ":", such as NSL: A, NSL: B. This usage is calledNamespace limitation (qualified)These names (such as NSL: a) are called qualified names ). The namespace in C ++ is similar to the relationship between directories and files in the operating system. Due to a large number of files, it is inconvenient to manage and easy to duplicate names, so people set up several subdirectories, put the files in different subdirectories. Files in different subdirectories can have the same name. Specify the file path when calling the file.

The role of a namespace:Is to create some mutually separated scopes, some global entities are separated.When the old names are called Li xiangguo, all three people have stood up and responded. This is a name conflict because they cannot identify which Li xiangguo the teacher wants. To avoid confusion of the same name, the school divides three students with the same name into three classes. In this way, when the name of the small class is Li xiangguo, only one person will respond. That is to say, the name within the scope of the class (that is, the scope of the class) is unique. If the principal is named at the school gathering, you need to find the student within the school, you need to consider the scope of the problem. If the principal is Li xiangguo, three students in the school will shout "to" because there are three students with the same name in the same scope. In order to distinguish the three students within the school, the principal must add a working number before the name, such as Li xiangguo in Class A of senior high school or Li xiangguo in Class B of Senior High School, that is, the limit on the working name is added. In this way, there will be no confusion.

You can set multiple namespaces as needed. Each namespace name represents a different namespace domain. Different namespaces cannot have the same name. In this way, entities in different databases can be put into different namespaces, or different namespaces can be used to conceal different entities. The global variables we used in the past can be understood as global namespaces. They are independent of all famous namespaces. They do not need to be declared using namespaces. They are actually implicitly declared by the system, exist in every program.

When declaring a namespace, not only variables, but also the following types can be included in curly brackets:

· Variables (which can be initialized );
· Constant;
· Number (can be a definition or Declaration );
· Struct;
· Class;
· Template;
· Namespace (in a namespace, another namespace is defined, that is, a nested namespace ).

For example

Namespace NSL
{ Const int rate = 0.08;// Constant
Doublepay;// Variable
Doubletax ()// Function
{Return a * rate ;}
Namespacens2// Nested namespace
{Int age ;}
}

Original post: http://hi.baidu.com/qingtian200888/blog/item/13437add3280d9325882dd48.html

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.