What exactly is a namespace and why is it necessary

后端 未结 3 1215
予麋鹿
予麋鹿 2020-12-16 02:39

I am learning C++ right now, and at the beginning of every project my instructor puts a line that says:

using namespace std;

I understand t

3条回答
  •  伪装坚强ぢ
    2020-12-16 02:40

    From cppreference.com:

    Namespaces provide a method for preventing name conflicts in large projects.

    Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.

    Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.

    A namespace works to avoid names conflicts, for example the standard library defines sort() but that is a really good name for a sorting function, thanks to namespaces you can define your own sort() because it won't be in the same namespace as the standard one.

    The using directive tells the compiler to use that namespace in the current scope so you can do

    int f(){
        std::cout << "out!" << std::endl;
    }
    

    or:

    int f(){
        using namespace std;
        cout << "out!" << endl;
    }
    

    it's handy when you're using a lot of things from another namespace.

    source: Namespaces - cppreference.com

提交回复
热议问题