#include<iostream>
using namespace std;
template<class t>
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(t r, t i){real=r;imag=i;}
Complex complex_add(Complex &c2);
void display();
template<class t1> friend Complex<t1> add_complex(Complex<t1> &c1, Complex<t1> &c2);
private:
t real;
t imag;
};
template<class t>
Complex<t> Complex<t>::complex_add(Complex &c2)
{
Complex<t> c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
template<class t>
void Complex<t>::display()
{
cout<<"("<<real<<","<<imag<<"i"<<")"<<endl;
}
template<class t>
Complex<t> add_complex(Complex<t> &c1,Complex<t> &c2)
{
Complex<t> c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
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();
Complex<int> c7;
c7=add_complex(c1,c2);
cout<<"c1+c2=";
c7.display();
Complex<double> c8;
c8=add_complex(c4,c5);
cout<<"c4+c5=";
c8.display();
return 0;
}
复数模板类
最新推荐文章于 2020-05-15 14:25:06 发布