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.
This provides a method of outputting the PT. Now, you can use this:
This gets translated into a call of
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” astd::ostream. There are quite a few things that inherit from it, meaning they arestd::ostreams 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 saystd::cout << p << '\n';because the result of printingpwill not returncoutfor you to use to print the newline.