No an error occurs when using using namespace std;
and std::cout
together. Can these two be used together?
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello world!";
return 0;
}
CodePudding user response:
There is no problem. In this statement
std::cout << "Hello world!";
there is used the qualified name lookup of the name cout
in the namespace std
.
You could also write
cout << "Hello world!";
and in this case there would be used the unqualified name lookup and the name cout
would be found due to the directive
using namespace std;
You could also include the using declaration like
using std::cout;
Pay attention to that you should avoid to use the using directive. It can be a reason of ambiguity. It is much better to use qualified names.
CodePudding user response:
The purpose of namespace
is to protect against collision. When you type in using namespace std;
it turns off that protection. This lets you use cout
, string
, vector
... without std::
resolution, but they may collide with other namespaces.
In some tutorials you may see using namespace std;
They put that in there to make the examples shorter without having to type in std::
every where. But that usage is limited to short examples. For actual code it is recommended not to add using namespace std;
You can always use std::cout
, std::string
, std::vector
etc. without worrying about collision.