Operator Overloading
What is Operator Overloading?
Operator overloading allows you to redefine the behavior of built-in operators for user-defined types, such as classes and structs. This can make your code more expressive and easier to read by allowing you to use familiar syntax with custom types.
To overload an operator, you need to create a member function or a friend function with the keyword operator followed by the operator symbol. The function should return the result of the operation.
For example, here's a simple implementation of a class called Complex that overloads the addition (+) operator:
class Complex {
public:
Complex(double real, double imag) : real_(real), imag_(imag) {}
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
private:
double real_;
double imag_;
};
With this implementation, you can add two Complex objects using the + operator, just like you would with built-in types:
Complex a(1, 2);
Complex b(3, 4);
Complex c = a + b;