#include <iostream> using namespace std; class Rectangle { private: int width; int height; public: Rectangle() { width = 1; height = 1; } Rectangle(int w, int h) { width = w; height = h; } int getWidth() const { return width; } int getHeight() const { return height; } // binary - (as method): "this - rect2" Rectangle operator-(const Rectangle& rect2) const { int width = this->getWidth() - rect2.getWidth(); int height = this->getHeight() - rect2.getHeight(); Rectangle result = { width, height }; return result; } // unary - (as method): "-this" , see below for implementation as standalone function Rectangle operator-() const { int width = -this->width; int height = -this->height; Rectangle result = { width, height }; return result; } Rectangle& operator+=(const Rectangle& rect2) { width = width + rect2.getWidth(); height = height + rect2.getHeight(); return *this; } }; Rectangle operator+(const Rectangle& rect1, const Rectangle& rect2) { int width = rect1.getWidth() + rect2.getWidth(); int height = rect1.getHeight() + rect2.getHeight(); Rectangle result = { width, height }; return result; } /* // unary - implemented as standalone function Rectangle operator-(const Rectangle& rect) { int width = -rect.getWidth(); int height = -rect.getHeight(); Rectangle result = { width, height }; return result; } */ void print(const Rectangle& rect) { cout << rect.getWidth() << ", " << rect.getHeight() << endl; } int main() { Rectangle r1 = { 10, 20 }; Rectangle r2 = { 50, 30 }; Rectangle r3 = r1 + r2; // ~ operator+(rect1, rect2), ~ add(r1, r2) print(r3); Rectangle r4 = -r3; // the unary - print(r4); return 0; }