Skip to main content

Posts

Showing posts with the label Overloading operator

Overloading the >> operator

The left operand of >> will always be an istream and the right operand will be whatever we want : #include <iostream> class Crazy { public: double a, b; }; istream & operator >> (istream &i, Crazy &c) { return i >> (c.a) >> (c.b); } int main(int argc, char **argv) { Crazy x; cin >> x; } The ostream can not be copied, and will always exist as a lvalue (by definition printing modifies its state), so you have to alway pass it by reference and return a reference : #include <iostream> void dumb1(ostream &s) {} void dumb2(ostream s) {} int main(int argc, char **argv) { dumb1(cout); dumb2(cout); } /usr/lib/gcc-lib/i586-pc-linux-gnu/2.95.1/../../../../include/g++-3/streambuf.h:12 ‘ios::ios(const ios &)’ is private Here the line 8 tries to pass the stream by value, thus to call a copy constructor, which is private.