Given two complex numbers, find the sum of the complex numbers using operator overloading. Write an operator overloading function ProblemSolution operator + (ProblemSolution const &P) which adds two ProblemSolution objects and returns a new ProblemSolution object.

Respuesta :

Answer:

Following are the program to this question:

#include<iostream>

using namespace std;

class Complex_number // defining a class Complex_number

{

private:      

int r1, i1; //defining private integer variable

public:    

Complex_number(int r= 0, int i =0) //defining parameterized constructor     {  

    r1 = r;  //holding value  

    i1 = i;  //holding value

 }  

   // using + operator overloading function

Complex_number operator + (Complex_number const &obc) //uing Complex_number class to add values  

 {      

   Complex_number total;//defining class variable

        total.r1 = r1 + obc.r1; //add real values  

       total.i1 = i1 + obc.i1; //add imagnary values  

      return total;//return total

}

void show() //defining method show  

{    

cout << r1 << " + i" << i1 << endl;//print value

}

};

 int main()//defining main method

{

  int real, imaginary; //defining integer variable  

 cout << "Enter the real number \n"; //print message  

cin >> real; //input real value  

cout << "Enter the imaginary number\n"; //print message    

cin >> imaginary;//input imaginary value  

  Complex_number ox(real, imaginary); // creating Complex_number object ox that accepts parameter to call constructor  

  cout << "Enter the real number\n";//print message    

cin >> real;//input real value  

cout << "Enter the imaginary number\n";//print message

  cin >> imaginary;//input imaginary value    

Complex_number oxa(real, imaginary);// creating Complex_number object oxa that accepts parameter to call constructor    

Complex_number oxb = ox + oxa; // creating another object of Complex_number that adds first and second input value     oxb.show();//calling show method

}

Output:

Enter the real number  1

Enter the imaginary number

1

Enter the real number

2

Enter the imaginary number

2

3 + i3  

Explanation:

for explanation please find attachment.

Ver imagen codiepienagoya