1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <string>
using namespace std;
class Complex
{
public:
Complex();
Complex(double r, double i)
void operator >>(ostream& out);
void operator <<(istream& in);
friend Complex operator *(const Complex& first, const Complex& second);.
friend Complex operator +(const Complex& first, const Complex& second);
friend Complex operator -(const Complex& first, const Complex& second);
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
void Complex::operator <<(istream& in)
{
char op;
char i;
in >> real >> op >> imag >> i;
if (op == '-')
{
imag = imag * -1;
}
return;
}
void Complex::operator >>(ostream& out) //prints a complex number to stream in the form a+bi
{
out << real << "+" << imag << "i" << endl;
if (imag < 0)
{
imag = imag + -1;
}
return;
}
Complex operator *(const Complex& first, const Complex& second)
{
double result_real = (first.real * second.real) - (first.imag * second.imag);
double result_imaginary = (first.real * second.imag) + (second.imag * second.real);
return Complex(result_real, result_imaginary);
}
Complex operator +(const Complex& first, const Complex& second)
{
double result_real = first.real + second.real;
double result_imaginary = first.imag + second.imag;
return Complex(result_real, result_imaginary);
}
Complex operator -(const Complex& first, const Complex& second)
{
double result_real = first.real - second.real;
double result_imaginary = first.imag - second.imag;
return Complex(result_real, result_imaginary);
}
int main() {
Complex a, b, c, d, e;
cout << "Enter the values for a in the form x+yi: ";
cin >> a;
cout << "Enter the values for b in the form x+yi: ";
cin >> b;
c = a + b;
d = a - b;
e = a*b;
cout << "a is: " << a << "b is : " << b;
cout << "a+b is: " << c << "a-b is: " << d << "a*b is: " << e;
return 0;
}
|