Basic Rules and Idioms for Operator Overloading in C++
Hello everyone! I'm learning C++ and trying to understand operator overloading. I wrote a simple class for working with complex numbers, but ran into a bunch of problems. Here's my code:
```cpp
class Complex {
public:
double real, imag;
Complex(double r, double i) : real(r), imag(i) {}
// Operator + overloading
Complex operator+(Complex other) {
return Complex(real + other.real, imag + other.imag);
}
// Operator == overloading
bool operator==(Complex other) {
return (real == other.real && imag == other.imag);
}
};
int main() {
Complex a(3.0, 4.0);
Complex b(1.0, 2.0);
Complex c = a + b; // Works
Complex d = 5.0 + a; // Error! Why?
if (c == d) {} // Works, but I heard this is wrong
}
```
No answers yet.
Log in to leave an answer