为什么我需要做'using namespace std'而不是"使用 std::cout"?

Why do I need to do 'using namespace std' instead of 'using std::cout'?

本文关键字:std cout 使用 namespace 为什么 using      更新时间:2023-10-16

everyone. 我了解到,为了避免命名空间冲突,通常需要使用std::cout而不是using namespace std编写代码。在下面的脚本中,我只使用 cout,如果我写 std:: cout 而不是使用命名空间 std;它不起作用。 谁能帮我理解为什么?一般来说,std::cout什么时候不起作用,我被迫使用using namespace 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;
}

您需要添加using std::string;以及using std::cout;才能使其正常工作,因为您不仅使用来自命名空间 std 的 cout,string还是您在代码中使用的namespace std的成员。

您的代码适用于:

using std::cout;

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

using std::string;

当您输入时:

using namespace std;

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