/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 李超
* 完成日期: 2012 年 4 月 4 日
* 版 本 号: 01.07.03
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:学会使用类模板,复数四则运算
* 程序输出:
* 程序头部的注释结束
编程风格,自己已尽力改善,如有建议,请多多指导,谢谢!
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 李超
* 完成日期: 2012 年 4 月 4 日
* 版 本 号: 01.07.03
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:学会使用类模板,复数四则运算
* 程序输出:
* 程序头部的注释结束
*/
头文件Complex.h
#include <iostream>
using namespace std;
template <class numtype>//声明一个模板,虚拟类型名为numtype
class Complex //类模板名为Complex
{
public:
Complex( ){real=0;imag=0;}
Complex(numtype r,numtype i){real=r;imag=i;}
Complex complexAdd(Complex &c2);//实现加法
Complex complexSubtract (Complex &c2);//实现减法
Complex complexMul (Complex &c2);//实现乘法
Complex complexDivision (Complex &c2);//实现除法
void display( ); //输出信息
private:
numtype real; //实数部分
numtype imag; //虚数部分
};
//实现加法
template <class numtype> Complex<numtype> Complex<numtype>::complexAdd(Complex &c2)//每一个成员函数的定义前,必须要声明类模板
{
Complex<numtype> c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
//实现减法
template <class numtype> Complex<numtype> Complex<numtype>::complexSubtract(Complex &c2)
{
Complex<numtype> c;
c.real=real - c2.real;
c.imag=imag - c2.imag;
return c;
}
//实现乘法
template <class numtype> Complex<numtype> Complex<numtype>::complexDivision (Complex &c2)
{
Complex<numtype> c;
c.real = (real * c2.real + imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
c.imag = (imag * c2.real - real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
return c;
}
//实现除法
template <class numtype> Complex<numtype> Complex<numtype>::complexMul (Complex &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> void Complex<numtype>::display( )
{
cout <<"("<<real<<","<<imag<<"i)" <<endl;
}
#include <iostream>
#include "Complex.h"
using namespace std;
int main( )
{ Complex<int> c1(3, 4), c2(5, -10), c3;
c3 = c1.complexAdd(c2);
cout <<"c1+c2 =";
c3.display( );
Complex<double> c4(3.1, 4.4), c5(5.3, -10.1), c6;
c6 = c4.complexAdd(c5);
cout <<"c4+c5 =";
c6.display( );
Complex<int> c7(2, 3), c8(9, 7), c9;
c9 = c7.complexSubtract (c8);
cout <<"c7-c8 =";
c9.display ();
Complex<double> c10(9, 3), c11(3, 7), c12;
c12 = c10.complexMul (c11);
cout <<"c10*c11 =";
c12.display ();
Complex<double> c13(4, 3), c14(9, 7), c15;
c15 = c13.complexSubtract (c14);
cout <<"c13/c14 =";
c15.display ();
system("pause");
return 0;
}
感觉类模板,太繁琐了,不过挺灵活的。
编程风格,自己已尽力改善,如有建议,请多多指导,谢谢!