You are required to create a class for dealing with complex numbers. In this particular
example we are only applying two arithmetic operations over complex number – addition
and subtraction. In complex numbers, we treat the real and imaginary part separately. You
need to define a constant char and assign it ‘i’, indicating the imaginary part. Also declare
two variables for denoting the real part and coefficient of the imaginary part. Define the
appropriate constructors, getters, setters and destructor as per the requirements.
You are required to create an object passing 2 arguments to its constructor, another
constant object with 2 arguments to its constructor. Add them both and store the resultant
object in a third instance by using the concept of copy constructor. Following are the
function prototypes,
Complex()
Complex(int, int)
Complex add(Complex)
void display()
void display() const
#include <iostream>
using namespace std;
class Complex {
public:
Complex();
Complex(int r, int i);
Complex(Complex& z);
~Complex();
int getReal() const;
void setReal(int r);
int getImag() const;
void setImag(int i);
Complex add(const Complex& z) const;
Complex sub(const Complex& z) const;
void display() const;
private:
const char ch;
int real;
int imag;
};
Complex::Complex() : real(0), imag(0), ch('i')
{}
Complex::Complex(int r, int i) : real(r), imag(i), ch('i')
{}
Complex::Complex(Complex& z)
: real(z.real), imag(z.imag), ch(z.ch)
{}
Complex::~Complex()
{}
int Complex::getReal() const
{
return real;
}
void Complex::setReal(int r)
{
real = r;
}
int Complex::getImag() const
{
return imag;
}
void Complex::setImag(int i)
{
imag = i;
}
Complex Complex::add(const Complex& z) const
{
int r = real + z.real;
int i = imag + z.imag;
return Complex(r, i);
}
Complex Complex::sub(const Complex& z) const
{
int r = real - z.real;
int i = imag - z.imag;
return Complex(r, i);
}
void Complex::display() const
{
if (real && imag) {
cout << '(' << real;
if (imag > 0) {
cout << " + " << imag << ch << ')';
}
else if (imag < 0) {
cout << " - " << -imag << ch << ')';
}
}
else if (imag) {
cout << imag << ch;
}
else {
cout << real;
}
}
int main() {
Complex z1(1, 2);
const Complex z2(3, -2);
Complex z3 = z1.add(z2);
z1.display();
cout << " + ";
z2.display();
cout << " = ";
z3.display();
cout << endl;
return 0;
}
Comments
Leave a comment