Question
ostream& operator<<(ostream& os, const PT& p)
{
os << "(" << p.x << "," << p.y << ")";
}
PT
is a structure and x
, y
are its members.
Can someone please explain what exactly the above line does. Can't the desired text be printed using cout
?
I came across this snippet of code from this site.
Solution
This provides a method of outputting the PT. Now, you can use this:
PT p;
std::cout << p;
This gets translated into a call of
operator<< (std::cout, p);
That matches your overload, so it works, printing the x and y values in brackets with less effort on the user's part. In fact, it doesn't have to be cout
. It can be anything that "is" a std::ostream
. There are quite a few things that inherit from it, meaning they are std::ostream
s as well, and so this works with them too. std::ofstream
, for file I/O, is one example.
One thing that the sample you found doesn't do, but should, though, is return os;
. Without doing that, you can't say std::cout << p << '\n';
because the result of printing p
will not return cout
for you to use to print the newline.
OTHER TIPS
It's a custom overload for operator<<
.
It means you can do this:
PT p = ...;
std::cout << p << "\n";
or this:
PT p = ...;
std::stringstream ss;
ss << p << "\n";
std::cout << ss;
or lots of other useful stuff.
However, it should be noted that the code you quoted won't work properly. It needs to return os
.
It allows the << operator to append the PT object to the stream. It seems the object has elements x and y that are added with a comma separator.
This operator << overloading for outputing object of PT class .
Here:
ostream& operator<<(ostream& os, const PT& p)
First param is for output stream where p will be appended. It returns reference to os for chaining like this:
cout << pt << " it was pt" << endl;