第九周—1.Complex类(运用<<和>>的重载)

 

/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: fun.cpp
* 作 者:谷志恒
* 完成日期:2013 年4月25日
* 版本号: v1.0
* 对任务及求解方法的描述部分:用类的成员函数完成运算符的重载,定义Complex类中的<<和>>的重载,实现输入和输出,改造原程序中对运算结果显示方式,是程序读起来更自然!
* 输入描述:略
* 问题描述:略
* 程序输出:如下
*/
#include <iostream>
using namespace std;
class Complex
{public:
	Complex(){real=0;imag=0;}
	Complex(double r,double i){real=r;imag=i;}
	Complex operator+(Complex &c2);
	Complex operator-(Complex &c2);
	Complex operator*(Complex &c2);
	Complex operator/(Complex &c2);
	friend ostream& operator <<(ostream&,Complex&);
	friend istream& operator >>(istream&,Complex&);
 private:
	double real;
	double imag;
};
//下面定义成员函数
Complex Complex::operator+(Complex &c2)//定义重载运算符+的含数
{
    return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator-(Complex &c2)//定义重载运算符-的含数
{
    return Complex(real-c2.real,imag-c2.imag);
}
Complex Complex::operator*(Complex &c2)//定义重载运算符*的含数
{
	return Complex(real*c2.real-imag*c2.imag,real*c2.imag+imag*c2.real);
}
Complex Complex::operator/(Complex &c2)//定义重载运算符/的含数
{
	return Complex((real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(imag*c2.real+real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));
}
ostream& operator <<(ostream& output,Complex& c)//定义重载运算符<<函数
{
	output<<"("<<c.real;
	if(c.imag>=0)output<<"+";//虚部为正数时,在虚部前加“+”号
	output<<c.imag<<"i)"<<endl;//虚部为负数时,在虚部前不加“+”号
	return output;;
}
istream& operator >>(istream& input,Complex& c)//定义重载运算符>>函数
{
	int a,b;
	char sign,i;
	do
	{
		cout<<"input a complex number(a+bi或a-bi):";
		input>>a>>sign>>b>>i;
	}
	while(!((sign=='+'||sign=='-')&&i=='i'));
	c.real=a;
	c.imag=(sign=='+')?b:-b;
	return input;
}
//下面是测试函数
int main()
{
	Complex c1(3,4),c2(5,-10),c3;
	cout<<"c1="<<c1<<endl;
	cout<<"c2="<<c2<<endl;
	c3=c1+c2;
	cout<<"c1+c2="<<c3<<endl;
	c3=c1-c2;
	cout<<"c1-c2="<<c3<<endl;
	c3=c1*c2;
	cout<<"c1*c2="<<c3<<endl;
	c3=c1/c2;
	cout<<"c1/c2="<<c3<<endl;
	return 0;
}


运行程序:

心得体会:我觉着我就像老师说的那种,看着书能编出来,但其中有些意义并不是很理解!不过我觉着从一点不会编到看着书能编出来,这也是进步,我还会继续加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值