#include <iostream>
using namespace std;
class Complex {
float x; // Real part
float y; // Imaginary part
public:
// Default constructor
Complex() : x(0), y(0) {}
// Overloaded + operator
Complex operator+(const Complex& c) const {
Complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return temp;
}
// Overloaded * operator
Complex operator*(const Complex& c) const {
Complex temp;
temp.x = (x * c.x) - (y * c.y);
temp.y = (y * c.x) + (x * c.y);
return temp;
}
// Friend function for input
friend istream& operator>>(istream& input, Complex& t) {
cout << "Enter the real part: ";
input >> t.x;
cout << "Enter the imaginary part: ";
input >> t.y;
return input;
}
// Friend function for output
friend ostream& operator<<(ostream& output, const Complex& t) {
output << t.x;
if (t.y >= 0)
output << "+" << t.y << "i";
else
output << t.y << "i"; // - sign is already included in the value of y
return output;
}
};
int main() {
Complex c1, c2, c3, c4;
cout << "Default constructor value:\n";
cout << c1 << endl;
cout << "\nEnter the 1st number\n";
cin >> c1;
cout << "\nEnter the 2nd number\n";
cin >> c2;
c3 = c1 + c2;
c4 = c1 * c2;
cout << "\nThe first number is " << c1 << endl;
cout << "The second number is " << c2 << endl;
cout << "The addition is " << c3 << endl;
cout << "The multiplication is " << c4 << endl;
return 0;
}
Output:
Default constructor value:
0+0i
Enter the 1st number
Enter the real part: 10
Enter the imaginary part: 595
Enter the 2nd number
Enter the real part: 9
Enter the imaginary part: 45
The first number is 10+595i
The second number is 9+45i
The addition is 19+640i
The multiplication is -26685+5805i
=== Code Execution Successful ===