/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:score.cpp
*作 者:惠睿
*完成日期:2015年4月10日
*版 本 号:v1.0
*
*问题描述:利用模板类,实现各种类型的复数的加减乘除运算。
*程序输入:无输入。
*程序输出:输出运算后的结果。
*/
#include <iostream>
using namespace std;
template <class numtype>
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(numtype r,numtype i)
{
real=r;
imag=i;
}
Complex complex_add(Complex &c1);
Complex complex_dec(Complex &c1);
Complex complex_mul(Complex &c1);
Complex complex_div(Complex &c1);
void display();
private:
numtype real;
numtype imag;
};
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &c1)
{
Complex<numtype> c;
c.real=real+c1.real;
c.imag=imag+c1.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_dec(Complex<numtype> &c1)
{
Complex<numtype> c;
c.real=real-c1.real;
c.imag=imag-c1.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_mul(Complex<numtype> &c1)
{
Complex<numtype> c;
c.real=real*c1.real;
c.imag=imag*c1.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_div(Complex<numtype> &c1)
{
Complex<numtype> c;
c.real=real/c1.real;
c.imag=imag/c1.imag;
return c;
}
template <class numtype>
void Complex<numtype>::display( )
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main( )
{
Complex<int> c1(3,4),c2(5,-10),c3;
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;
c6=c4.complex_add(c5);
cout<<"c4+c5=";
c6.display( );
cout<<endl;
Complex<int> p1(3,4),p2(5,-10),p3;
p3=p1.complex_dec(p2);
cout<<"p1-p2=";
p3.display();
Complex<double> p4(3.1,4.4),p5(5.34,-10.21),p6;
p6=p4.complex_dec(p5);
cout<<"p4-p5=";
p6.display( );
cout<<endl;
Complex<int> t1(3,4),t2(5,-10),t3;
t3=t1.complex_mul(t2);
cout<<"t1*t2=";
t3.display( );
Complex<double> t4(3.1,4.4),t5(5.34,-10.21),t6;
t6=t4.complex_mul(t5);
cout<<"t4*t5=";
t6.display( );
cout<<endl;
Complex<int> b1(3,4),b2(5,-10),b3;
b3=b1.complex_div(b2);
cout<<"b1/b2=";
b3.display( );
Complex<double> b4(3.1,4.4),b5(5.34,-10.21),b6;
b6=b4.complex_div(b5);
cout<<"b4/b5=";
b6.display( );
return 0;
}
运行结果: