Does this mean that inside of the iostream file the developers that created it made a namespace called std and put the functions cin and cout into the namespace called std |
cin and cout are global objects, not functions. But yes, that's what it means.
"::" is known as the "scope resolution" operator. It can apply to both class scope and namespace scope. If you have
1 2 3
|
class A {
void printStuff()
};
| |
Then you must do
1 2 3 4
|
void A::printStuff()
{
// ...
}
| |
in the (non-inline) implementation to differentiate it from a free function (non-class function) that might also be called "void printStuff()".
It
resolves the name of printStuff as belonging to the class A instead of being a free function. In the same way, std::cout resolves 'cout' as being inside the std namespace. Both use the :: syntax.
If you define the function within the class definition itself, it is implicitly inline, and you don't need the A::
1 2 3 4 5 6
|
class A{
void printStuff()
{
// ...
}
};
| |
since it's already clear that the function is within the class.
If I create a function in main, why don't I have to put main::printStuf{}? |
You can't create functions within functions. So you can't create a function in main.
_____________________
Another, more complete example, using :: to access the static member of a class and namespace.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
class A {
public:
static void printStuff()
{
std::cout << "A::printStuff()\n";
}
};
namespace experiment {
void printStuff()
{
std::cout << "experiment::printStuff()\n";
}
}
void printStuff()
{
std::cout << "free function: printStuff()\n";
}
int main()
{
A::printStuff();
experiment::printStuff();
printStuff();
}
| |
A::printStuff()
experiment::printStuff()
free function: printStuff()
|