Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - Why using namespace std is necessary here?

#include <iostream>
using namespace std;

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

If I remove the 2nd statement,the build will fail.

Why is it necessary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because cout and endl are contained inside the std namespace.

You could remove the using namespace std line and put instead std::cout and std::endl.

Here is an example that should make namespaces clear:

Stuff.h:

namespace Peanuts
{
  struct Nut
  {
  };
}


namespace Hardware
{
  struct Nut
  {
  };
}

When you do something like using namespace Hardware you can use Nut without specifying the namespace explicitly. For any source that uses either of these classes, they need to 1) Include the header and 2) specify the namespace of the class or put a using directive.

The point of namespaces are for grouping and also to avoid namespace collisions.

Edit for your question about why you need #include :

#include <iostream> includes the source for cout and endl. That source is inside the namespace called std which is inside iostream.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...