每个人。 我了解到,为了避免名称空间冲突,通常需要使用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;
}
您需要添加使用std::string;的和使用std::cout;
的以使其工作,因为您不仅使用名称空间std中的cout,
string
也是您在代码中使用的名称空间std
的成员。
您的代码可以正常工作:
using std::cout;
语句,但编译器也必须知道您当前使用的cout
的位置(实际上是std::string
)。 必须定义:
using std::string;
输入时:
using namespace std;
它调用名为std
的整个命名空间,其中包含作为C++标准库添加的各种特性,然后您不需要为该命名空间的那些函数/类/变量使用前缀std::
。