#include <iostream>
using namespace std;
template <class numtype>
class Complex
{
private:
numtype real,img;
public:
Complex ()
{
real=0;
img=0;
}
Complex(numtype r,numtype i)
{
real=r; //类声明中的每一个T,将被对象定义时提供的实际类型代替
img=i;
}
Complex complex_add(Complex &);
Complex complex_minu(Complex &);
Complex complex_multiply(Complex &);
Complex complex_divide(Complex &);
void display();
};
template<class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex &c1)
{
Complex c;
c.real=real+c1.real;
c.img=img+c1.img;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_minu(Complex &c1)
{
Complex c;
c.real=real-c1.real;
c.img=img-c1.img;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_multiply(Complex &c1)
{
Complex c;
c.real=real*c1.real+img*c1.img;
c.img=real*c1.img+img*c1.real;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_divide(Complex &c1)
{
Complex c;
numtype d=c1.real*c1.real+c1.img*c1.img;
c.real=(real*c1.real+img*c1.img)/d; //此处有危险未排除:除法溢出
c.img=(img*c1.real-real*c1.img)/d;
return c;
}
template<class numtype>
void Complex<numtype>::display()
{
cout<<"("<<real<<","<<img<<"i)"<<endl;
}
int main( )
{
Complex<int> c1(3,4),c2(5,-10),c3; //实部和虚部是int型
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6; //实部和虚部是double型
c6=c4.complex_add(c5);
cout<<"c4+c5=";
c6.display( );
//下面测试减法、乘法和除法
Complex<int> c7(3,4),c8(5,-10),c9;
cout<<"c7-c8=";
c9=c7.complex_minu(c8);
c9.display();
Complex<int> c10,c11;
cout<<"c1*c2=";
c10=c1.complex_multiply(c2);
c10.display();
cout<<"c7-c8=";
c11=c1.complex_divide(c2);
c11.display();
return 0;
}