提问者:小点点

为什么我需要“using namespace std”而不是“using std::cout”?


每个人。 我了解到,为了避免名称空间冲突,通常需要使用std::cout而不是使用namespace std来编写代码。 在下面的脚本中,我只使用cout,如果我编写std::cout而不是使用名称空间std; 不管用。 有谁能帮我理解一下原因吗? 通常,当std::cout不能工作,我被迫使用使用名称空间std时?



#include <iostream>
#include <string>
using std::cout; //if writing here "using namespace std;" instead, the code does not work

class MyClass{
public:
    string name;
    MyClass (string n)
    {
        name=n;
        cout<<"Hello "<<name;
    }
};


int main()
{
    MyClass MyObj("Mike");

return 0;
}

共2个答案

匿名用户

您需要添加使用std::string;的和使用std::cout;以使其工作,因为您不仅使用名称空间std中的cout,string也是您在代码中使用的名称空间std的成员。

匿名用户

您的代码可以正常工作:

using std::cout;

语句,但编译器也必须知道您当前使用的cout的位置(实际上是std::string)。 必须定义:

using std::string;

输入时:

using namespace std;

它调用名为std的整个命名空间,其中包含作为C++标准库添加的各种特性,然后您不需要为该命名空间的那些函数/类/变量使用前缀std::