/* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 作 者:申玉迪
* 完成日期:2014 年 4 月 10 日
* 版 本 号:v1.0
* 问题描述: 复数模板类
*/
#include <iostream>
using namespace std;
template <class numtype>
class Complex
{
public:
Complex()
{
real=0;
image=0;
}
Complex (numtype r,numtype i)
{
real=r;
image=i;
}
Complex complex_add(Complex &);
Complex complex_minus(Complex &);
Complex complex_product(Complex &);
Complex complex_consult(Complex &);
void display();
private:
numtype real;
numtype image;
};
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(6,8),c9;
cout<<"c7-c8=";
c9=c7.complex_minus(c8);
c9.display();
Complex<int> a1(3,4),a2(6,8),a3;
cout<<"a1*a2=";
a3=a1.complex_product(a2);
a3.display();
Complex<double> a4(3,4),a5(6,8),a6;
cout<<"a4/a5=";
a6=a4.complex_consult(a5);
a6.display();
return 0;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex &t)
{
Complex<numtype> c;
c.real=real+t.real;
c.image=image+t.image;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_minus(Complex &t)
{
Complex<numtype> c;
c.real=real-t.real;
c.image=image-t.image;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_product(Complex &t)
{
Complex<numtype> c;
c.real=real*t.real;
c.image=image*t.image;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_consult(Complex &t)
{
Complex<numtype> c;
c.real=real/t.real;
c.image=image/t.image;
return c;
}
template <class numtype>
void Complex<numtype>::display()
{
cout<<"("<<real<<","<<image<<"i)"<<endl;
}
一开始运行时有十几个错误,怎么办,也没发现错误,就找了一个别人写好的,发现居然败在了一个template <class numtype>上和Complex <numtype>,写一个不就够了嘛,干嘛非要写那么多...................