include and using namespace in C++

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

for using cout, I need to specify both:

#include

and

using namespace std;

4条回答
  •  心在旅途
    2021-02-06 03:44

    iostream is the name of the file where cout is defined. On the other hand, std is a namespace, equivalent (in some sense) to java's package.

    cout is an instance defined in the iostream file, inside the std namespace.

    There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write

    std::cout, indicating the scope.

    std::cout<<"Hello world"<

    To avoid the std:: everywhere, you can use the using clause.

    cout<<"Hello world"<

    They are two different things. One indicates scope, the other does the actual inclusion of cout.

    In response to your comment

    Imagine that in iostream two instances named cout exist, in different namespaces

    namespace std{
       ostream cout;
    }
    namespace other{
       float cout;//instance of another type.
    }
    

    After including , you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope

提交回复
热议问题