A simple example shows you how to use the C ++ namespace.

Source: Internet
Author: User

I am about to look for a job soon. Recently, I have worked very hard to review my work. It is said that all the companies now have a relatively heavy Foundation for the test interview, so I have carefully thought about what I 've done before. Recent articles record some of the basics I have encountered during my review, but I still ignore things and hope to help my children's shoes.

Using namespace STD is very familiar to everyone. All identifiers in the C ++ standard library are defined in a namespace named STD. Due to the concept of namespace, when using any identifier of the C ++ standard library, You can have three options (here I suddenly think that Kong Yiji says there are four ways to write the Z text ):

1. directly specify the identifier
For example, use STD: cout instead of cout. Complete statement: STD: cout <1 <STD: Endl;

2. Use the Using Keyword
Using STD: cout; Using STD: Endl; Using STD: CIN;
The above program can be written as cout <1 <Endl;

3. Using namespace std
The most convenient method is to use using namespace STD. In this way, all identifiers defined in the namespace STD are valid as if they were declared as global variables. The preceding statement can be written as follows:
Cout <1 <Endl;

What if we want to define a namespace by ourselves? The following simple example clearly illustrates this process.

// Name. h
Namespace
{
Int fun ();
}

Namespace B
{
Int fun ();
}

// Name. cpp
# Include "name. H"

Int A: Fun ()
{
Return 1;
}

Int B: Fun ()
{
Return 2;
}

// Main. cpp
# Include <iostream>
# Include "name. H"

Using namespace STD;
Using namespace B;

Void main (void)
{
Cout <"result =" <fun () <Endl;
}

Because namespace B is used, the execution result of the program is: Result = 2. Of course, you can try the namespace method mentioned above in 3. Pai_^

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.