What requires me to declare “using namespace std;”

2020-02-10 12:23发布

This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare

using namespace std;

in C++ programs?

12条回答
一夜七次
2楼-- · 2020-02-10 13:03

Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::

查看更多
等我变得足够好
3楼-- · 2020-02-10 13:04

Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:

// cstdio
namespace std
{
  // ...
  int printf(const char* ...);
  // ...
}

.

// stdio.h
#include <cstdio>
using namespace std;

Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-10 13:14

Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.

However,

using namespace std;

is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like

using std::string;
查看更多
我想做一个坏孩纸
5楼-- · 2020-02-10 13:16

You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:

using std::cout;

By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.

Rgds Layne

查看更多
Bombasti
6楼-- · 2020-02-10 13:17

It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do

using namespace std;

unless you want to specify the namespace when calling functions within another namespace, like so:

std::cout << "cout is declared within the namespace std";

You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.

查看更多
做个烂人
7楼-- · 2020-02-10 13:19

The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:

#include <iostream>
using namespace std;

...
cout << "Hi" << endl;

vs.

#include <iostream>

...
std::cout << "Hi" << std::endl;
查看更多
登录 后发表回答