Custom Operator Overloading
🔴 Advanced
📖 Definition
Operator overloading allows user-defined classes to redefine standard C++ operators (e.g. +, ==, <<, []) to provide intuitive syntax for custom domain types.
💡 Code Example
#include <iostream>
class Complex {
public:
double real, imag;
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& rhs) const {
return Complex(real + rhs.real, imag + rhs.imag);
}
};
int main() {
Complex c1(1.5, 2.5), c2(2.0, 3.0);
Complex c3 = c1 + c2;
std::cout << "Sum: " << c3.real << " + " << c3.imag << "i\n";
return 0;
}