/*
* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 作 者:马广明
* 完成日期:2014 年 4 月 9 日
* 问题介绍: 模板类--加减乘除
* 版 本 号:v1.0
*/
#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);
Complex complex_minus(Complex &c2);
Complex complex_multiply(Complex &c2);
Complex complex_divide(Complex &c2);
void display( );
private:
T real;
T imag;
};
template<class T>
Complex<T> Complex<T>::complex_add(Complex<T> &c2)
{
Complex<T> c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
template <class T>
Complex<T> Complex<T>::complex_minus(Complex <T> &c2)
{
Complex <T> c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
template <class T>
Complex<T> Complex<T>::complex_multiply(Complex <T> &c2)
{
Complex <T> c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
template <class T>
Complex<T> Complex<T>::complex_divide(Complex <T> &c2)
{
Complex <T> c;
T d=c2.real*c2.real+c2.imag*c2.imag;
c.real=(real*c2.real+imag*c2.imag)/d;
c.imag=(imag*c2.real-real*c2.imag)/d;
return c;
}
template<class T>
void Complex<T>::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( );
c6=c4.complex_minus(c5);
cout<<"c4-c5=";
c6.display( );
c6=c4.complex_multiply(c5);
cout<<"c4*c5=";
c6.display( );
c6=c4.complex_divide(c5);
cout<<"c4/c5=";
c6.display( );
return 0;
}
模板----加减乘除
最新推荐文章于 2023-05-14 09:58:29 发布