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

Categories

0 votes
1.3k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...