Problems with duplicate names in C + +

Source: Internet
Author: User

See C + + video Tutorials-Fan Lie (2.91G) Video Learning notes collation.

Why should 1.c++ introduce namespaces (namespace)?

C + + introduces the concept of namespaces in order to avoid duplicate name problems, such as avoiding duplication of function names or variable name conflicts.

2. For example: Use the name space to write, you can have three name B variable name, but their values are different.

#include <iostream>
namespace a
{
    int b=5;
}
Namespace C
{
    int b=8;
}
int main ()
{
    int b=9;
    std::cout<<b<< "" <<a::b<< "" <<c::b<<std::endl;
    return 0;
}

Print results:

3. But if we don't use namespaces, obviously we can't define it:

int b=5;

int b=8;

int b=9;

This code is wrong and cannot be compiled.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

4. When renaming conflicts:

#include <iostream>
namespace a
{
    int b=5;
}
Namespace C
{
    int b=8;
}
int main ()
{
    using namespace A;
    using namespace C;
    int b=9;
    std::cout<<b;
    return 0;
}

Print results:

The output is the value 9 in main function main.

If we comment out the int b=9 in the main function; You will not be able to compile and a B-ambiguous symbol error appears.

Author: cnblogs Nebula

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.