C++ operator overloading
Created By: chatGPT
Operator Overloading in C++ allows developers to redefine the way operators work for user-defined types (classes). This feature provides a way to use operators in a more intuitive way, making code more readable and easier to understand. You can overload most operators to facilitate their use with objects of a class. Below is an example that demonstrates operator overloading using a simple
Complex
class to handle complex numbers.class Complex {
private:
float real;
float imag;
public:
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overloading + operator
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
// Overloading << operator for output
friend std::ostream &operator<<(std::ostream &out, const Complex &c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};
In this example, we declare a
Complex
class that includes two private member variables to store the real and imaginary parts of a complex number. The constructor initializes these parts, and we overload the +
operator to allow the addition of two Complex
objects. The output operator (<<
) is also overloaded to display complex numbers in a user-friendly format.int main() {
Complex c1(1.5, 2.5);
Complex c2(3.5, 4.5);
Complex c3 = c1 + c2; // Using the overloaded + operator
std::cout << "c1: " << c1 << "\n";
std::cout << "c2: " << c2 << "\n";
std::cout << "c3 (c1 + c2): " << c3 << "\n";
return 0;
}
In the
main
function, we create two Complex
objects, c1
and c2
. By using the overloaded +
operator, we can easily add these two objects to get c3
. When printing the complex numbers with the overloaded <<
operator, the output will be clear and succinct./* Output:
c1: 1.5 + 2.5i
c2: 3.5 + 4.5i
c3 (c1 + c2): 5.0 + 7.0i
*/