#include <iostream>
#include <cmath>
using namespace std;
template <class numtype>
class Complex
{
private:
numtype real;
numtype imag;
public:
Complex()
{
real=imag=0;
}
Complex(numtype a,numtype b)
{
real=a;
imag=b;
}
void display();
Complex complex_add(Complex &cc); //执行加法运算
Complex complex_minus(Complex &cc); //执行减法运算
Complex complex_muliply(Complex &cc); //执行乘法运算
Complex complex_divided(Complex &cc); //执行除法运算
};
template <class numtype>
void Complex<numtype>::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &cc) //执行加法运算
{
Complex<numtype> c;
c.real=real+cc.real;
c.imag=imag+cc.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_minus(Complex<numtype> &cc)//执行减法运算
{
Complex<numtype> c;
c.real=real-cc.real;
c.imag=imag-cc.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_muliply(Complex<numtype> &cc)//执行乘法运算
{
Complex<numtype> c;
c.real=real*cc.real-imag*cc.imag;
c.imag=real*cc.imag+imag*cc.real;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_divided(Complex<numtype> &cc)//执行除法运算
{
Complex<numtype> c;
c.real=(real*cc.real+imag*cc.imag)/(cc.real*cc.real+cc.imag*cc.imag);
c.imag=(real*cc.imag+imag*cc.real)/(cc.real*cc.real+cc.imag*cc.imag);
return c;
}
int main( )
{
//下面测试加法
Complex<int> c1(3,4),c2(5,-10),c3; //实部和虚部是int型
cout<<"c1=";
c1.display( );
cout<<"c2=";
c2.display( );
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6; //实部和虚部是double型
cout<<"c4=";
c4.display( );
cout<<"c5=";
c5.display( );
c6=c4.complex_add(c5);
cout<<"c4+c5=";
c6.display( );
//下面测试减法
c3=c1.complex_minus(c2);
cout<<"c1-c2=";
c3.display( );
c6=c4.complex_minus(c5);
cout<<"c4-c5=";
c6.display( );
//下面测试乘法
c3=c1.complex_muliply(c2);
cout<<"c1*c2=";
c3.display( );
c6=c4.complex_muliply(c5);
cout<<"c4*c5=";
c6.display( );
//下面测试除法
c3=c1.complex_divided(c2);
cout<<"c1/c2=";
c3.display( );
c6=c4.complex_divided(c5);
cout<<"c4/c5=";
c6.display( );
return 0;
}
输出结果: