Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Define a complex class so that the following program can use it with correct res

ID: 3922839 • Letter: D

Question

Define a complex class so that the following program can use it with correct results:

#include <iostream>

using namespace std;

#include "complex0.h" // to avoid confusion with complex.h

int main()

{   

complex a(3.0, 4.0); // initialize to (3,4i)

complex c;

cout << "Enter a complex number (q to quit): ";

while (cin >> c)

{   

cout << "c is " << c << ' ';

cout << "complex conjugate is " << ~c << ' ';

cout << "a is " << a << ' ";

cout << "a + c is " << a + c << ' ';

cout << "a - c is " << a - c << ' ';

cout << "a * c is " << a * c << ' ';

cout << "2 * c is " << 2 * c << ' ';

cout << "Enter a complex number (q to quit): ";

}

cout << "Done! ";

return 0;

}

Note that you have to overload the << and >> operators. Standard C++ already has complex support, in a complex header file, so use complex0.h to avoid conflicts. Use const whenever warranted.

Here is a sample run of the program:

Enter a complex number (q to quit):

real: 10

imaginary: 12

c is (10,12i)

complex conjugate is (10,-12i)

a is (3,4i)

a + c is (13,16i)

a - c is (-7,-8i)

a * c is (-18,76i)

2 * c is (20,24i)

Enter a complex number (q to quit):

real: q

Explanation / Answer

#include<iostream>
using namespace std;
public class Complex(){
   public:
   float real;
   float img;//imaginary
  
   Complex(){
       real = 0;
       img = 0;
   }
   Complex(float a, float b){
       real = a;
       img = b;
   }
  
   friend ostream &operator<<( ostream &output,const Complex &C ){
        output << "(" << C.real << "," << C.img<<"i)";
        return output;          
    }
    friend istream &operator>>( istream &input, Complex &C ){
        input >> C.real >> C.img;
        return input;          
    }
  
   Complex operator+(const Complex &C){
       Complex n;
       n.real = this.real + C.real;
       n.img = this.img + C.img;
       return n;
   }
   Complex operator-(const Complex &C){
       Complex n;
       n.real = this.real - C.real;
       n.img = this.img - C.img;
       return n;
   }
   Complex operator*(float x){
       Complex n;
       n.real = this.real*x;
       n.img = this.img*x;
       return n;
   }
   Complex operator*(const Complex c){
       Complex n;
       n.real = this.real*C.real - this.img*C.img;
       n.img = this.real*C.img + this.img*C.real;
       return n;
   }
}
Complex operator*(float x, const Complex &C){
   Complex n;
   n.real = C.real*x;
   n.img = C.img*x;
   return n;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote