What is namespace used for, in C++?

后端 未结 4 1268
灰色年华
灰色年华 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.

提交回复
热议问题