您的位置:首页 > 其它

第九周 项目1--定义一目运算符-和Complex中的<< >>的重载

2014-04-22 14:14 549 查看
*Copyright(c)2013,烟台大学计算机学院学生
*All rights reserved.
*文件名称:
*作者:尚振伟
*完成日期:2014年4月22日
*版本号:v0.1
*对任务及求解方法的描述部分:
*输入描述:无
*问题描述:定义复数类重载运算符+、-、*、/  << >>,使之能用于复数的加减乘除输出和输入
*程序输入:
*程序输出:
*问题分析:
*算法设计:
*我的程序:
*/
#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)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
Complex Complex::operator-(Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
Complex Complex::operator*(Complex &c2)
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=real*c2.imag+imag*c2.real;
return c;
}
Complex Complex::operator/(Complex &c2)
{
Complex 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;
}
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)
{
cout<<"input real part and imaginary part of complex number:";
input>>c.real>>c.imag;
return input;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1,c2,c3;
cin>>c1>>c2;
cout<<"c1="<<c1;
cout<<"c2="<<c2;
c3=c1+c2;
cout<<"c1+c2="<<c3;
c3=c1-c2;
cout<<"c1-c2="<<c3;
c3=c1*c2;
cout<<"c1*c2="<<c3;
c3=c1/c2;
cout<<"c1/c2="<<c3;
return 0;
}


结果展示:



心得体会:五一九天假期要好好过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐