C++ overloading of << or >> example and explanation -
this question has answer here:
i learning c++ , don't understand how << , >> operator overloading works.
can please provide example and/or explanation of method overloads either operator?
class { int x; public: a(int _x) : x(_x){} friend ostream& operator<<(ostream& os, elem); }; ostream& operator<<(ostream& os, elem) { os << elem.x; return os; }
then can call
std::cout << a(5); //prints 5
explanation: you're doing in here, making friend function class. we're making friend because want refer private fields. if have struct, don't have declare friend.
we're returning ostream&
can "chaining" - cout << x << y
wouldn't work if returned ostream
. we're taking reference os same reason, plus want actual stream(otherwise you'd end writing copy). , we're taking elem a
, because it's going printed. then, print os whatever want - remember, can print elements ostream can print(e.g. ints, strings, etc.). print os
, , return it(chaining). remember, calling cout<<x
equivalent calling operator<<(cout, x)
ps. answered specific << operator overloading, because that's first came mind, , thought you're struggling with. didn't make clear whether want overload operator ostream, or class, can use function.
Comments
Post a Comment