第七周任务三

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* 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;
}


主函数main.cpp

#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;
}
感觉类模板,太繁琐了,不过挺灵活的。
编程风格,自己已尽力改善,如有建议,请多多指导,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值