每个人。
我了解到通常需要使用 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
的成员(member)您在代码中使用的。
关于c++ - 为什么我需要做 'using namespace std' 而不是 'using std::cout' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62497362/