Operators may also be overloaded as so-called "friend" functions. The following generates code equivalent to the + operator we defined on the previous page:
class Vector { private: // stuff... public: friend Vector operator+(const Vector& left, const Vector& right); }; Vector operator+(const Vector& left, const Vector& right) { // ... code here. Note that this is not a member // function, but it has access to all the private // members of Vector because it is declared as a "friend" } Note: an overloaded operator need not be a friend of the class(es) on which it operates.
Two operators are very commonly overloaded in C++, because they provide a handy idiomatic way of doing input and output:
class Foo { public: // ...some stuff, then: friend ostream& operator<<(ostream& out, const Foo& foo); friend istream& operator>>(istream& in, Foo& foo); private: int x, y; }; ostream& operator<<(ostream& out, const Foo& foo) { out << '(' << foo.x << ',' << foo.y << ')'; } istream& operator>>(istream& in, Foo& foo) { char dummy; in >> dummy >> foo.x >> dummy >> foo.y >> dummy; } // Code using the above operators Foo f; cin >> f; // cin is an istream subclass instance cout << f << endl; // cout is an ostream subclass instance