This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Monday, February 27, 2023

Write a program to add two complex numbers of two different classes.

 Here's a program to add two complex numbers of two different classes:

#include <iostream>
using namespace std;
class Complex1 {

private:
    double real;
    double imag;

public:

    Complex1(double r = 0, double i = 0) {
        real = r;
        imag = i;
    }

    void display() {
        cout << real << " + " << imag << "i" << endl;
    }
};

class Complex2 {
private:

    double real;
    double imag;

public:
    Complex2(double r = 0, double i = 0) {
        real = r;
        imag = i;
    }
    void display() {
        cout << real << " + " << imag << "i" << endl;
    }
    Complex2 operator+(const Complex1& c1) {
        Complex2 temp;
        temp.real = real + c1.real;
        temp.imag = imag + c1.imag;
        return temp;
    }
};

int main() {
    Complex1 c1(3.5, 5.2);
    Complex2 c2(1.2, 2.3);
    Complex2 c3 = c2 + c1;
    cout << "c1 = ";
    c1.display();
    cout << "c2 = ";
    c2.display();
    cout << "c3 = ";
    c3.display();
    return 0;
}

In this program, we have two classes, Complex1 and Complex2. Both classes represent complex numbers, but they are implemented differently. Complex1 stores the real and imaginary parts as private data members, and has a constructor to initialize them. Complex2 also has private real and imaginary parts, but it defines an operator+ function that takes a Complex1 object as an argument and adds it to itself to get a new Complex2 object.

In the main function, we create a Complex1 object c1 and a Complex2 object c2. We then add c1 and c2 using the + operator defined in Complex2 and store the result in a new Complex2 object c3. Finally, we display all three complex numbers using the display member function defined in both classes.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget