Write a program in C++ with a complex constructor to add the given two complex numbers A =_ and B = _. The program should print the given complex number and its sum.
#include<iostream.h>
#include<conio.h>
class complex
{
private:
float x; //real
float y; //imaginary
public:
complex() { }
complex(float real, float imag)
{ x=real;
y=imag;
}
void display()
{
cout<<x<<"+"<<y<<"i \n";
}
complex operator + (complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return ( temp );
}
};
void main()
{
clrscr();
complex c1, c2, c3;
c1 = complex (3.2,2.5);
c2 = complex (4.5,2.5);
c3 = c1 + c2;
cout<<"First Object:";
c1.display();
cout<<"\nSecond Object:";
c2.display();
cout<<"\n-----------------------------------";
cout<<"\nResult:";
c3.display();
getch();
}
Explanation
This C++ program defines a class named complex
to represent complex numbers. The class has two private data members x
and y
which represent the real and imaginary parts of the complex number respectively.
The complex
class also has a default constructor and a parameterized constructor that takes two arguments, real
and imag
. The parameterized constructor initializes the x
and y
data members of the object being created with the values passed as arguments.
The complex
class also has a display
method which prints the complex number in the format x+yi
.
The complex
class has overloaded the +
operator using the operator+
method. This operator allows us to add two complex numbers.
In the main
function, three complex
objects c1
, c2
, and c3
are created. c1
is initialized with the values 3.2
and 2.5
using the parameterized constructor. c2
is initialized with the values 4.5
and 2.5
using the parameterized constructor.
The program then uses the overloaded +
operator to add c1
and c2
, and the result is stored in c3
. Finally, the display
method is used to print the values of c1
, c2
, and c3
.
Output:
First Object:3.2+2.5i
Second Object:4.5+2.5i
-----------------------------------
Result:7.7+5i
This program adds two complex numbers, c1
and c2
, and prints the result in the format x+yi
. The result is stored in c3
, which is also a complex
object. The display
the method is used to print the values of c1
, c2
, and c3
.