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

1. Write the class definition for a class called complex. Complex numbers have t

ID: 3551512 • Letter: 1

Question

1. Write the class definition for a class called complex.

Complex numbers have the form

        realPart + imaginaryPart * i

where I is the square of (-1)

Use double variable to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values of 0 in case no initializers are provided. Provide public member functions that perform the following tasks:

a). setComplex function to set complex number to set the real part and imaginary part of the complex number

b). displayComplex function to print complex number in the form (a, b), where a is the real part and b is the imaginary part.

2. Write a C++ program to test your class by using the following main function.

int main ()

{

complex c1(1, 2), c2(3, 4), c3;

c1.display();

c2.display()

c3.display();

c3.setComplex(5, 6);

c3.display();

return 0;

}

Explanation / Answer

#include <iostream>


using namespace std;


class Complex {

private:

double real;

double imag;

public:

Complex();

Complex(double r, double i);

void setComplex(double r, double i);

void display();

};


Complex::Complex() {

real = 0;

imag = 0;

}


Complex::Complex(double r, double i) {

real = r;

imag = i;

}


void Complex::setComplex(double r, double i) {

real = r;

imag = i;

}


void Complex::display() {

cout << "(" << real << ", " << imag << ") ";

}

int main ()


{


Complex c1(1, 2), c2(3, 4), c3;


c1.display();


c2.display();


c3.display();


c3.setComplex(5, 6);


c3.display();


return 0;


}