/*
* 程序的版权和版本声明部分
* 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;
}
运行程序:
心得体会:我觉着我就像老师说的那种,看着书能编出来,但其中有些意义并不是很理解!不过我觉着从一点不会编到看着书能编出来,这也是进步,我还会继续加油!