What is namespace used for, in C++?

后端 未结 4 1255
灰色年华
灰色年华 2020-12-03 06:09

What is namespace used for, in C++?

using namespace std;
相关标签:
4条回答
  • 2020-12-03 06:10

    Namespace usually is used to prevent naming conflicts. So, One place where namespace comes into picture is

    class ABC{
    //  Does something for me.
    };
    
    class ABC{
    // Does something for you..
    };
    
    int main() {
        ABC myABC;
        return 0;
    }
    

    This will give a compilation error as the system will not know which class is to be considered. Here the concept of namespace comes into picture.

    namespace My{
        class ABC{
        //  Does something for me.
        };
    }
    namespace Your{   
        class ABC{
        // Does something for you..
        };
    }
    using My::ABC
    // We explicitly mention that My ABC is to be used. 
    int main() {
        ABC myABC;
        return 0;
    }
    

    Code will be much organized with the usage of namespaces.

    0 讨论(0)
  • 2020-12-03 06:13

    One could ask, simple pair of curly braces {} are sufficient to resolve name conflict. Still why have a NameSpace. A quick answer as Tamer mentioned above is that with NameSpace we get the ability to open the same scope in another file.

    0 讨论(0)
  • 2020-12-03 06:25

    It's used for preventing name confilct, so you may have two classes with the same name in different namespaces.

    Also it's used for categorizing your classes, if you have seen the .net framework, you will see that namespaces are used for categorizing the classes. For example, you may define a namespace for the employee classes, and a namespace for the tasks classes, and both namespaces are within a namespace for the company classes, since a namespace may contain sub namespaces.

    The same namespace may exist in different files, so using it may be useful because it will make you able to directly use all the classes in the namespaces in every #included file.

    That's what I remember for now.

    0 讨论(0)
  • 2020-12-03 06:30

    Namespace is used to prevent name conflicts.

    For example:

    namespace foo {
        class bar {
            //define it
        };
    }
    
    namespace baz {
        class bar {
            // define it
        };
    }
    

    You now have two classes name bar, that are completely different and separate thanks to the namespacing.

    The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.

    0 讨论(0)
提交回复
热议问题