Can someone clarify what this means at the top of the file in C++?
using std::cout;
Thanks
It means that from then on in the code, when we type cout
we mean std::cout
It injects the cout
defined in namespace std
into the current namespace. We use this over using namespace std
as this is much more controlled; not every single std
name will be injected with this statement.
using namespace std;
before? Because this would do the same thing (Except for endl
swap
and tons of other stuff)
Commented
Oct 13, 2012 at 22:11
using namespace std;
but i think i see it now
Commented
Oct 13, 2012 at 22:13
It's a namespace declaration. Allows you to type out cout
instead of std::cout
and is generally preferred instead of using namespace std;
The using
declaration introduces the name cout
to the global namespace as a synonym for std::cout
.
It is related with the "namespace" concept. In order to avoid name collisions (variables, classes, whatever, which have the same name in different files), you can put your code into a namespace as following:
namespace exampleNS
{
class A { ... }
void aFunction (...){ ... }
}
When you are inside namespace exampleNS
, you can refer to class A
using just the name, but from outside you need to write exampleNS::A
.
If you want to save the verbosity of adding the namespace before a name that you use a lot (and you are sure does not collide with anything inside your current namespace), you can write that using
statement.
Mostly all standard library utilities are inside namespace std
, as for instance the variables cout
and cin
. In your case, your code is not inside the namespace std
: you can choose between writing std::cout
each time you want to print something, or write using std::cout
at the beginning and then using it as cout
in the code.
using A::B
Where A
is a namespace, means that accessibility of B
does not require the prefixing of it's derivative. Note that this is only relative to the scope in which it is placed. If placed in a lower-level scope, it's function will not have any affect in the outer scope.