Answer to Question #295645 in C++ for Gokul K

Question #295645

Create a class called Complex to represents complex numbers. Complex class contains following members





1. Two private float data members such as real and imag.





2. Two public member function such as read() to read input for complex numbers from user and print() to print the complex numbers(refer sample output for output format).





3. Two operator functions:





First operator function(it should be friend) is overloading the binary operator + to add and return two complex objects.





Second operator function is overloading the greater than operator(>) to check whether object1 is greater than object2. If object1 is greater than object2, then return true otherwise return false.

1
Expert's answer
2022-02-09T10:40:49-0500
#include <iostream>
using namespace std;


class Complex {
    float real;
    float imag;


public:
    void read() {
        cin >> real >> imag;
    }
    void print() {
        cout << "(" << real << ", " << imag << ")";
    }
    Complex operator+(Complex z) {
        Complex c;
        c.real = real + z.real;
        c.imag = imag + z.imag;
        return c;
    }
    bool operator>(Complex z) {
        return (real*real + imag*imag) >
               (z.real*z.real + z.imag*z.imag);
    }
};


int main() {
    Complex z1, z2, z3;


    z1.read();
    z2.read();
    
    z3 = z1 + z2;


    z1.print();
    cout << " + ";
    z2.print();
    cout << " = ";
    z3.print();
    cout << endl;


    if (z1 > z2) {
        z1.print();
        cout << " is greater than ";
        z2.print();
        cout << endl;
    }
    else {
        z1.print();
        cout << " is not greater than ";
        z2.print();
        cout << endl;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog