Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

n C++, operator overloading is a feature that allows operators, such as +, -, *, /, and <<, to be overloaded with custom behavior for user-defined types. Operator overloading allows you to use the same syntax with your own classes as you would with built-in types, making your code more natural and intuitive.

Here's an example of operator overloading:

class Complex {
private:
    double real;
    double imag;
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}
    
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }
    
    friend ostream& operator<<(ostream& out, const Complex& c) {
        out << "(" << c.real << ", " << c.imag << ")";
        return out;
    }
};

int main() {
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;
    
    cout << c1 << " + " << c2 << " = " << c3 << endl;
    
    return 0;
}

In this example, we have defined a Complex class that represents complex numbers. We have overloaded the + operator to allow adding two complex numbers together, and we have overloaded the << operator to allow printing complex numbers to the console.

In the main function, we create two complex numbers c1 and c2 and add them together using the + operator. We then print the result using the overloaded << operator.

Operator overloading is useful when you want to make your code more expressive and natural by allowing operators to work with your own classes. However, it should be used with care, as overloading operators can sometimes make your code less readable and more error-prone. When overloading operators, you should follow the conventions and semantics of the built-in operators to avoid confusing users of your code.

  • No labels