Answer to Question #180848 in C++ for Ramakrishna Reddy

Question #180848

. Write a program to perform binary operator overloading for a class named "data". The details of operators to be overloaded are:


+ will subtract the numbers


- will divide the numbers


*will add the numbers


/ will multiply the numbers


1
Expert's answer
2021-04-14T04:22:11-0400
#include<iostream>
using namespace std;

class ComplexNumber {
   private:
    float real;
    float imag;

   public:
    // Constructor to initialize real and imag to 0
    ComplexNumber() : real(0), imag(0) {

    }

    void input() {
        cout << "Enter real and imaginary parts respectively: ";
        cin >> real;
        cin >> imag;
    }

    // Overload the - operator
    ComplexNumber operator - (const ComplexNumber& obj) {
        ComplexNumber temp;
        temp.real = real / obj.real;
        temp.imag = imag / obj.imag;
        return temp;
    }
    // Overload the + operator
    ComplexNumber operator + (const ComplexNumber& obj) {
        ComplexNumber temp;
        temp.real = real - obj.real;
        temp.imag = imag - obj.imag;
        return temp;
    }
    // Overload the * operator
    ComplexNumber operator * (const ComplexNumber& obj) {
        ComplexNumber temp;
        temp.real = real + obj.real;
        temp.imag = imag + obj.imag;
        return temp;
    }
    // Overload the / operator
    ComplexNumber operator / (const ComplexNumber& obj) {
        ComplexNumber temp;
        temp.real = real * obj.real;
        temp.imag = imag * obj.imag;
        return temp;
    }

    void output() {
        if (imag < 0)
            cout << "Output Complex number: " << real << imag << "i";
        else
            cout << "Output Complex number: " << real << "+" << imag << "i";
    }
};

int main() {
    ComplexNumber complex1, complex2, result;

    cout << "Enter first complex number:\n";
    complex1.input();

    cout << "Enter second complex number:\n";
    complex2.input();

   // complex1 calls the operator function
   // complex2 is passed as an argument to the function
    result = complex1 - complex2;
    result.output();
cout<<"\n"<<endl;
    result = complex1 + complex2;
    result.output();
cout<<"\n"<<endl;
    result = complex1 * complex2;
    result.output();
cout<<"\n"<<endl;
    result = complex1 / complex2;
    result.output();



    return 0;
}

Output:

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
APPROVED BY CLIENTS