C++: using namespace and #include

后端 未结 2 627
孤街浪徒
孤街浪徒 2020-12-24 06:58

In C++ what is the difference between the #include directive and using namespace? Also do you store your namespaces as separate files and what is

2条回答
  •  粉色の甜心
    2020-12-24 07:21

    In C++, #include is used to add files to your project while namespace is used to keep your objects in logical modules (namespace does not apply to C)

    For example, you might have a vector class in file "vector.h" so you include it in your project.

    vector is a part of a large library (the standard library) STD, so you can access it with

    std::vector
    

    However since programmers are lazy and don't want to write std:: all over the place (the standard library has many many very useful parts), you can write

    using namespace std
    

    on the top of your file. This will tell the compiler that everytime it sees a type (such as vector), also check in the namespace std because the definition might be there. This way, the following statements become equivalent.

    std::vector
    vector
    

    In vector.h, you should see something like

    namespace std
    {
       class vector { /* Implementation */ }
    }
    

    So #include is to add files, while using namespace is to keep your code cleaner and packaged in "meaningful" libraries. You can omit using namespace when programming but you absolutely need the #include

提交回复
热议问题