为什么在这里需要使用命名空间std?

sym*_*ony 3 c++ syntax

#include <iostream>
using namespace std;

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除第二个语句,则构建将失败.

为什么有必要?

Bri*_*ndy 12

因为coutendl包含在std命名空间内.

你可以删除using namespace std线,改为std::coutstd::endl.

这是一个应该使名称空间清晰的示例:

Stuff.h:

namespace Peanuts
{
  struct Nut
  {
  };
}


namespace Hardware
{
  struct Nut
  {
  };
}
Run Code Online (Sandbox Code Playgroud)

当你做类似的事情时using namespace Hardware,可以使用Nut而不明确指定命名空间.对于使用这些类中的任何一个的任何源,它们需要1)包含头和2)指定类的命名空间或放置using指令.

命名空间的重点是分组,也避免命名空间冲突.

编辑您的问题为什么需要#include:

#include <iostream>包括用于所述源coutendl.该源位于名为std的名称空间内,该名称空间位于iostream中.