include and using namespace in C++

前端 未结 4 1762
日久生厌
日久生厌 2021-02-06 02:57

for using cout, I need to specify both:

#include

and

using namespace std;

4条回答
  •  抹茶落季
    2021-02-06 03:49

    cout is logically defined within iostream. By logically, I mean it may actually be in the file iostream or it may be in some file included from iostream. Either way, including iostream is the correct way to get the definition of cout.

    All symbols in iostream are in the namespace std. To make use the the cout symbol, you must tell the compiler how to find it (i.e. what namespace). You have a couple of choices:

    // explicit
    std::cout << std::endl;
    
    // import one symbol into your namespace (other symbols must still be explicit)
    using std::cout;
    cout << std::endl;
    
    // import the entire namespace
    using namespace std;
    cout << endl;
    
    // shorten the namespace (not that interesting for standard, but can be useful
    // for long namespace names)
    namespace s = std;
    s::cout << s::endl;
    

提交回复
热议问题