class_complex_1
class_complex_1
PRACTICAL 1:
Implement a class Complex which represents the Complex Number data type. Implement
the
following operations:
1.Constructor (including a default constructor which creates the complex number
0+0i).
2.Overloaded operator+ to add two complex numbers.
3.Overloaded operator* to multiply two complex numbers.
4.Overloaded << and >> to print and read Complex Numbers.
*/
#include <iostream>
using namespace std;
class complex
{
float realp, imagp;
public:
complex() : realp(0), imagp(0) {} // Default constructor with initializer list
complex(float x, float y); // Parameterized constructor
complex operator+(const complex &) const; // Addition operator
complex operator*(const complex &) const; // Multiplication operator
friend istream &operator>>(istream &, complex &);
friend ostream &operator<<(ostream &, const complex &);
};
complex::complex(float x, float y) : realp(x), imagp(y) {} // Parameterized
constructor definition
istream &operator>>(istream &din, complex &c)
{
cout << "Enter real part of complex number: ";
din >> c.realp;
cout << "Enter imaginary part of complex number: ";
din >> c.imagp;
return din;
}
ostream &operator<<(ostream &dout, const complex &c)
{
dout << c.realp;
if (c.imagp >= 0)
dout << " + " << c.imagp << "i";
else
dout << " - " << -c.imagp << "i";
dout << endl;
return dout;
}
complex complex::operator+(const complex &c) const
{
complex temp;
temp.realp = realp + c.realp;
temp.imagp = imagp + c.imagp;
return temp;
}
complex complex::operator*(const complex &c) const
{
complex mul;
mul.realp = (realp * c.realp) - (imagp * c.imagp);
mul.imagp = (imagp * c.realp) + (realp * c.imagp);
return mul;
}
int main()
{
complex c1(1.2, 2.2), c2, c3;
cout << "Complex number 1 is: " << c1;
cout << "Enter complex number 2:\n";
cin >> c2;
cout << "Complex number 2 is: " << c2;
c3 = c1 + c2;
cout << "\nAddition of two complex numbers is: " << c3;
c3 = c1 * c2;
cout << "\nMultiplication of two complex numbers is: " << c3;
return 0;
}
/*
Output:
Complex number 1 is: 1.2 + 2.2i
Enter complex number 2:
Enter real part of complex number: 2
Enter imaginary part of complex number: 3
Complex number 2 is: 2 + 3i
Addition of two complex numbers is: 3.2 + 5.2i
Multiplication of two complex numbers is: -4.2 + 8i
Theory
The code defines a class complex to represent and manipulate complex numbers in C+
+. It includes features like addition, multiplication, and input/output operations
for complex numbers. Complex numbers have two parts: a real part and an imaginary
part, and the class encapsulates these operations using operator overloading.
Definition
a: Real part
b: Imaginary part
i: Imaginary unit (
Algorithm
1. Constructor
0+0𝑖.
Default Constructor: Initializes the complex number to