// Samples of overloading operators in four different ways // ************************** METHOD 1 *********************************** // OVERLOADING AS NON-MEMBER FUNCTIONS, IF ONLY DATA ACCESSORS ARE PROVIDED // Note: this would require the protoypes to be in the header file, after the // end of the class declaration. bool operator==(const Point& p1, const Point& p2) { return p1.x() == p2.x() && p1.y() == p2.y(); } istream& operator>>(istream& in, Point& p) { double x,y; in >> x >> y; if (in) p = Point(x,y); return in; } ostream& operator << (ostream& out, const Point& p) { out << p.x() << ' ' << p.y(); return out; } // ************************** METHOD 2 *********************************** // OVERLOADING AS NON-MEMBERS USING MEMBER FUNCTIONS; EG sameAs, read and print // Note: this would require the protoypes to be in the header file, after the // end of the class declaration. bool operator==(const Point& p1, const Point& p2) { return p1.sameAs(p2); } istream& operator>>(istream& in, Point& p) { p.read(in); return in; } ostream& operator<<(ostream& out, const Point& p) { p.print(out); return out; } // ************************** METHOD 3 *********************************** // OVERLOADING AS A MEMBER FUNCTION // Note: this would require the protoype to be inside the class declaration bool Point::operator==(const Point& p) const { return xValue == p.xValue && yValue == p.yValue; } // Note: we cannot overload the insertion and extraction operators as member // functions since the left hand operand is not a Point object, but a stream // ************************** METHOD 4 *********************************** // OVERLOADING AS NON-MEMBER FRIEND FUNCTIONS // Note: this requires that the class declare these to be friends. // i.e. inside the class declaration, you would include the following // friend prototypes: friend bool operator==(const Point& p1, const Point& p2); friend istream& operator>>(istream& in, Point& p); friend ostream& operator<<(ostream& out, const Point& p); bool operator==(const Point& p1, const Point& p2) { return p1.xValue == p2.xValue && p1.yValue == p2.yValue; } istream& operator>>(istream& in, Point& p) { double x,y; in >> x >> y; if (in) { p.xValue = x; p.yValue = y; } return in; } ostream& operator<<(ostream& out, const Point& p) { out << p.xValue << ' ' << p.yValue; return out; }