I understand that the &
character has various uses in c++, but I'm having trouble understanding what its function is in the code sample below (taken from here) (not its use in the left argument, but its use in std ostream&
.
std::ostream& operator<< (std::ostream &out, const Point &point)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ")";
return out;
}
I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.
As far as I can see (which isn't very far at all), std::ostream
is an class, which, when instantiated, can, via the operator <<
, can be fed strings etc. to output to console. Then &out
in the code above is a reference to an instance of std::ostream
, (which will be std::cout
?), which inside the function is fed point.m_x
etc. and then returned so that multiple <<
operations can be performed.
I'm guessing the first instance of the & character is somehow communicating that the << operator defined in std::ostream is to be modified in some way, in order to allow it to function with members of the example Point class, but I want to have a better understanding than that.