C++ Operator Overloading
Give operators a meaning for your own classes. You can't overload ::, ., .*, ?: or sizeof.
#include <iostream>
using namespace std;
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
Complex operator+(const Complex &o) const { return Complex(re + o.re, im + o.im); }
bool operator==(const Complex &o) const { return re == o.re && im == o.im; }
friend ostream& operator<<(ostream &out, const Complex &c) {
return out << c.re << " + " << c.im << "i";
}
};
int main() {
Complex a(2, 3), b(1, 4);
Complex c = a + b;
cout << c << endl;
cout << (c == Complex(3, 7)) << endl;
}
3 + 7i
1
Track your progress through the C++ course