Operator Overloading provides a clean, intuitive syntax for user-defined classes by extending the behavior of built-in C++ operators without altering their precedence or arity.
<<)#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// Overloading '+' operator as a member function
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// Overloading '<<' stream operator as a friend function
friend std::ostream& operator<<(std::ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};
int main() {
Complex c1(3.5, 2.5);
Complex c2(1.5, 4.5);
Complex c3 = c1 + c2; // Clean, mathematical syntax!
std::cout << "Result: " << c3 << std::endl; // Output: 5 + 7i
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Precedence and associativity of operators.
Using friend functions for stream overloading.
Overloading operator= for move semantics.