Avatar ·

Grundregeln und Idiome der Operatorüberladung in C++

Hallo zusammen! Ich lerne C++ und versuche, die Operatorüberladung zu verstehen. Ich habe eine einfache Klasse für komplexe Zahlen geschrieben, aber auf eine Reihe von Problemen gestoßen. Hier ist mein Code: ```cpp class Complex { public: double real, imag; Complex(double r, double i) : real(r), imag(i) {} // Überladung des Operators + Complex operator+(Complex other) { return Complex(real + other.real, imag + other.imag); } // Überladung des Operators == 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; // Funktioniert Complex d = 5.0 + a; // Fehler! Warum? if (c == d) {} // Funktioniert, aber ich habe gehört, dass das falsch ist return 0; } ``` Fragen: 1. Warum kompiliert `5.0 + a` nicht, obwohl `a + 5.0` funktioniert? 2. Habe ich `operator+` richtig überladen? Was ist das "Idiom der Rückgabe nach Wert"? 3. Wie überlade ich `operator==` korrekt?