“using namespace” in c++ headers

后端 未结 9 2346
失恋的感觉
失恋的感觉 2020-11-22 01:32

In all our c++ courses, all the teachers always put using namespace std; right after the #includes in their .h files. This seems to me

9条回答
  •  孤独总比滥情好
    2020-11-22 01:50

    With regards to "Is there some way to undo [a using declaration]?"

    I think it is useful to point out that using declarations are affected by scope.

    #include 
    
    {   // begin a new scope with {
        using namespace std;
        vector myVector;  // std::vector is used
    }   // end the scope with }
    
    vector myOtherVector;   // error vector undefined
    std::vector mySTDVector // no error std::vector is fully qualified
    

    So effectively yes. By limiting the scope of the using declaration its effect only lasts within that scope; it is 'undone' when that scope ends.

    When the using declaration is declared in a file outside of any other scope it has file-scope and affects everything in that file.

    In the case of a header file, if the using declaration is at file-scope this will extend to the scope of any file the header is included in.

提交回复
热议问题