第六周项目6(1)-复数模板类

来源:互联网 发布:心事谁人知 编辑:程序博客网 时间:2024/05/16 12:28
/* *Copyright (c) 2014, 烟台大学计算机学院 *All rights reserved. *文件名称:week6-6.cpp *作者:高赞 *完成日期:2015年 4 月 15 日 *版本号:v1.0 * * 问题描述:用类模板完成复数的加减乘除*/#include <iostream>using namespace std;template <class numtype>class Complex{private:    numtype real;    numtype imag;public:    Complex()    {        real=0;        imag=0;    }    Complex(numtype r,numtype i):real(r),imag(i) {}    Complex complex_add(Complex &c2);//加法    Complex complex_sub(Complex &c2);//减法    Complex complex_mul(Complex &c2);//乘法    Complex complex_div(Complex &c2);//除法    void display();};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_sub(c5);    cout<<"c4-c5=";    c6.display( );    Complex<int> c7(1,2),c8(3,4),c9;    c9=c7.complex_mul(c8);    cout<<"c7×c8=";    c9.display();    Complex<double> c10(3.1,4.2),c11(1.3,2.4),c12;    c12=c10.complex_mul(c11);    cout<<"c10÷c11=";    c9.display();    return 0;}template<class numtype>Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &c2){    Complex<numtype> c;    c.real=real+c2.real;    c.imag=imag+c2.imag;    return c;}template<class numtype>Complex<numtype> Complex<numtype>::complex_sub(Complex<numtype> &c2){    Complex<numtype> c;    c.real=real-c2.real;    c.imag=imag-c2.imag;    return c;}template<class numtype>Complex<numtype> Complex<numtype>::complex_mul(Complex<numtype> &c2){    Complex<numtype> c;    c.real=real*c2.real-imag*c2.imag;    c.imag=imag*c2.real+real*c2.imag;    return c;}template<class numtype>Complex<numtype> Complex<numtype>::complex_div(Complex<numtype> &c2){    Complex<numtype> c;    numtype 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 numtype>void Complex<numtype>::display(){    cout<<"("<<real<<","<<imag<<"i)"<<endl;}

 

 

各处模板声明各种忘-_-#

                                             
0 0