[Operator Overloading] Complex Number


Submit solution

Points: 10
Time limit: 0.06s
Memory limit: 12M

Author:
Problem type
Allowed languages
C++

Operator Overloading

#include <iostream>
using namespace std;

// Class representing a complex number
class Complex {
private:
    // Private members for the real and imaginary parts
    double real;
    double imag;

public:
    // Constructor to initialize the complex number
    Complex(double r, double i) : real(r), imag(i) {}

    // Overloaded + operator to add two complex numbers
    Complex operator+(const Complex& other) const {
        // Create a new Complex object with the sum of real and imaginary parts
        return Complex(real + other.real, imag + other.imag);
    }

    // Display function to print the complex number
    void display() {
        cout << real << "+i " << imag << endl;
    }
};

int main() {
    // Create instances of the Complex class
    Complex c1(2.5, 3.7);
    Complex c2(1.8, 2.2);

    // Use the overloaded + operator to add complex numbers
    Complex result = c1 + c2;

    // Display the result of the addition
    cout << "Result of addition: ";
    result.display();

    return 0;
}

Modify the given C++ program to include a new member function in the Complex class that calculates the multiplication of the complex number. After obtaining user input for two complex numbers, use this new member function to display the add and multiplication of each complex number.


Comments

There are no comments at the moment.