您的位置:首页 > 其它

第九周(项目一)——实现复数类中的运算符重载。

2014-04-22 14:22 281 查看
/*
02.02.*烟台大学计算机学院学生
03.03.*All right reserved.
04.04.*文件名称*烟台大学计算机学院学生
05.05.*All right reserved.
06.06.*文件名称:实现复数类中的运算符重载
07.07.*作者:王洪海
08.08.*完成日期:2013年4月22日
09.09.*版本号:v1.0
10.10.*对任务及求解方法的描述部分:实现复数类中的运算符重载
11.11.*/
#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);
Complex operator-();
friend ostream& operator<<(ostream &,Complex &);
friend istream& operator>>(istream &,Complex &);
void display();
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;
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 t;
t.real=-real;
t.imag=-imag;
return t;
}
ostream& operator<<(ostream &output,Complex &t)
{
output<<"("<<t.real;
if(t.imag>=0)
output<<"+";
output<<t.imag<<"i)";
return output;
}
istream& operator>>(istream &input,Complex &t)
{
input>>t.real>>t.imag;
return input;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1(3,4),c2,c3;
cout<<"  c1=";
cout<<c1<<endl;
c3=-c1;
cout<<" -c1=";
cout<<c3<<endl;
cout<<"输入c2的值:";
cin>>c2;
c3=c1+c2;
cout<<"c1+c2=";
cout<<c3<<endl;
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
return 0;
}


运行结果,如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐