Namespace-what you know and what you don't know

Source: Internet
Author: User

Namespace is a feature of C ++. It can provide solutions for name conflicts in large projects. However, manyProgramStaff ignored its use.

Here are a few examples to illustrate some of its usage.

1. Using declarations

It provides a local alias for the objects declared in the namespace;

Namespace A <br/>{< br/> int F (INT); <br/> int I; <br/>}// note, the semicolon is not required here </P> <p> using a: F; // introduce the f function in a; </P> <p> int F (INT ); // The global function </P> <p> int main () <br/> {<br/> F (1); // The ambiguity is incorrect! <Br/> int I; // defines the local variable <br/> using a: I; // error! Just like writing another line of int I; <br/>}

Using declarations only references the names in the previously defined namespace and is invalid for subsequent declarations:

Namespace A <br/>{< br/> Class X {}; // #1 <br/> int y (); // #2 <br/> int F (double); // #3 <br/>}</P> <p> using a: X; // only #1 <br/> using a: Y; // only #2 <br/> using a: F; // only #3 </P> <p> namespace A <br/>{< br/> class y {}; // #4 <br/> int F (INT); // #5 <br/>}</P> <p> int main () <br/> {<br/> X; // OK <br/> Y; // error, #4 invisible <br/> F (1 ); // call #3! <Br/>}</P> <p>

 

2. Using directives

The name of the entire namespace will be introduced and can be referenced to the namespace name defined later in this instruction!

Namespace A <br/>{< br/> Class X {}; <br/> int F (double ); <br/>}</P> <p> using namespace A; </P> <p> void F () <br/>{< br/> X; // A: x <br/> Y; // error! <Br/> F (1); // OK: int F (double) <br/>}</P> <p> namespace A <br/>{< br/> class y {}; <br/> int F (INT ); <br/>}</P> <p> int main () <br/>{< br/> X; // :: x <br/> Y; // A: y <br/> F (1); // OK: int F (INT) <br/>}< br/>

 

Therefore, do not use using in the header file to avoid unexpected conflicts. Using in CPP cannot appear before include.

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.