>c1;coutcin>>c2" />

实验三:多态性答案—专业版

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.定义一个复数类,通过重载运算符实现复数的四则运算、求负运算和赋值运算。其中,要求加法“+”和减法“-”用友元函数实现重载,其他运算符用成员函数实现重载。

//main.cpp:

#include "complex.h"

int main(int argc , char *argv[])

{

COMPLEX c1,c2;

cout<<"请输入第一个复数:\n";

cin>>c1;

cout<<"请输入第二个复数:\n";

cin>>c2;

cout<<"第一个复数是:"<

cout<<"第二个复数是:"<

cout<<"c1+c2的结果为:"<

cout<<"c1-c2的结果为:"<

cout<<"c1*c2的结果为:"<

cout<<"c1/c2的结果为:"<

cout<<"-c2的结果为:"<<-c2<

return 0;

}

// complex.h

#include

using namespace std;

class COMPLEX{

protected:

double real;

double image;

public:

COMPLEX(double r=0, double i=0);

COMPLEX(const COMPLEX& other);

friend COMPLEX operator+(const COMPLEX& left,const COMPLEX& right);

friend COMPLEX operator-(const COMPLEX& left,const COMPLEX& right);

COMPLEX operator*(const COMPLEX& other);

COMPLEX operator/(const COMPLEX& other);

COMPLEX operator-();

COMPLEX operator=(const COMPLEX& other);

friend ostream& operator <<(ostream& stream, COMPLEX& obj);

friend istream& operator >>(istream& stream, COMPLEX& obj); };

COMPLEX::COMPLEX(double r, double i)

{

real=r;

image=i;

}

COMPLEX::COMPLEX(const COMPLEX& other)

{

real=other.real;

image=other.image;

}

COMPLEX COMPLEX::operator*(const COMPLEX& other)

{

COMPLEX temp;

temp.real=real*other.real-image*other.image;

temp.image=real*other.image+other.real*image;

return temp;

}

COMPLEX COMPLEX::operator/(const COMPLEX& other)

{

COMPLEX temp;

double v=other.real*other.real+other.image*other.image;

if (v!=0.0)

{

temp.real=(real*other.real+image*other.image)/v;

temp.image=(image*other.real-real*other.image)/v;

return temp;

}

cout<<"除法无效\n";

return temp;

}

COMPLEX COMPLEX::operator-()

{

COMPLEX temp;

temp.real=-real;

temp.image=-image;

return temp;

}

COMPLEX COMPLEX::operator=(const COMPLEX& other)

{

real=other.real;

image=other.image;

return *this;

}

/////////////////////////////////////////////////////

// 友元函数不是类的成员函数!!

COMPLEX operator+(const COMPLEX& left, const COMPLEX& right) {

COMPLEX temp;

temp.real=left.real+right.real;

temp.image=left.image+right.image;

return temp;

}

COMPLEX operator-(const COMPLEX& left, const COMPLEX& right) {

COMPLEX temp;

temp.real=left.real-right.real;

temp.image=left.image-right.image;

return temp;

}

ostream& operator <<(ostream& stream, COMPLEX& obj)

{

stream<

if(obj.image>0) stream<<"+"<

else if(obj.image<0) stream<

return stream;

}

istream& operator >>(istream& stream, COMPLEX& obj)

{

cout<<"输入实部:";

stream>> obj.real;

cout<<"输入虚部:";

stream>> obj.image;

return stream;

}

相关文档
最新文档