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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
#include <iostream>
using namespace std;
template <class T> class Complex
{
private:
double real;
double imag;
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(double x, double y)
{
real = x;
imag = y;
}
void setReal(double x)
{
real = x;
}
void setImag(double x)
{
imag = x;
}
double getReal()
{
return real;
}
double getImag()
{
return imag;
}
Complex& operator =(Complex &x)
{
real = x.getReal();
imag = x.getImag();
return *this;
}
Complex operator +(Complex &x)
{
Complex temp;
temp.setReal(x.getReal() + real);
temp.setImag(x.getImag() + imag);
return temp;
}
Complex operator -(Complex &x)
{
Complex temp;
temp.setReal(x.getReal() + real);
temp.setImag(x.getImag() + imag);
return temp;
}
Complex operator *(Complex &x)
{
Complex temp;
temp.setReal(x.getReal() * real);
temp.setImag(x.getImag() * imag);
return temp;
}
};
template<class T>
bool operator ==(Complex<T>& a, Complex<T>& b)
{
return (a.getReal() == b.getReal() && a.getImag() == b.getImag());
};
template<class T>
ostream& operator<<(ostream& out, Complex& c)
{
out << c.getReal() << '+' << c.getImag() << 'i';
return(out);
}
int main()
{
Complex <int, int> x(1, 2);
Complex <int, int> y(2, 3);
Complex <int, int> z, w, v;
z = x + y;
w = x - y;
v = x * y;
if (z == w)
cout << " z = w" << endl;
else
cout << " z != w" << endl;
cout << "z= " << z << endl << "w= " << w << endl << "v= " << v << endl;
Complex <float, float> x2(1.3, 2.3);
Complex <float, float> y2(2.4, 3.4);
Complex <float, float> z2, w2, v2;
z2 = x2 + y2;
w2 = x2 - y2;
v2 = x2 * y2;
if (z2 == w2)
cout << " z2 = w2" << endl;
else
cout << " z2 != w2" << endl;
system("PAUSE");
return 0;
}
|