I am learning c++ and I don't understand how the << and >> operator overloading works.
Can someone please provide an example and/or explanation of a method that overloads either operator?
I am learning c++ and I don't understand how the << and >> operator overloading works.
Can someone please provide an example and/or explanation of a method that overloads either operator?
class A
{
int x;
public:
A(int _x) : x(_x){}
friend ostream& operator<<(ostream& os, A elem);
};
ostream& operator<<(ostream& os, A elem)
{
os << elem.x;
return os;
}
Then you can call
std::cout << A(5); //prints 5
Explanation: What you're doing in here, is making friend function for some class. We're making it friend because we want to refer to its private fields. If you have struct, you don't have to declare it as friend.
We're returning ostream&
so that we can do "chaining" - cout << x << y
wouldn't work if you returned just ostream
.
We're taking reference to os for the same reason, plus we want the actual stream(otherwise you'd end up writing into some copy). And we're taking elem A
, because it's going to be printed. Then, we print to os whatever we want - but remember, you can only print elements that ostream can print(e.g. ints, strings, etc.). We print to os
, and then we return it(chaining).
Remember, calling cout<<x
is equivalent to calling operator<<(cout, x)
PS. I answered about this specific << operator overloading, because that's first what came into my mind, and I thought that this is what you're struggling with. You didn't make clear whether you want to overload operator for ostream, or just for some class, so you can use it as some function.