定义一个复数类,用友元函数实现对双目运算符+和*的运算符重载,使其适用于复数运算

 #include <cmath>

#include <iostream.h>

class CComplex

{

#define err 0.00000001

double _x,_y;

public:

CComplex(double x=0,double y=0):_x(x),_y(y){}

CComplex operator+(const CComplex&z);

CComplex operator*(const CComplex&z);

friend ostream&operator <<(ostream&os,const CComplex&z);

friend istream&operator >>(istream&is,CComplex&z);

};

int main()

{

CComplex z1(0,1.2);

CComplex z2(1,1.2);

cout<<z1+z2<<endl;

cout<<z1*z2<<endl;

cin>>z1;

cout<<z1<<endl;

return 0;

}

CComplex CComplex::operator+(const CComplex&z)

{

CComplex c;

c._x=_x+z._x;

c._y=_y+z._y;

return c;

}

CComplex CComplex::operator*(const CComplex&z)

{

CComplex c;

c._x=_x*z._x-_y*z._y;

c._y=_x*z._y+_y*z._x;

return c;

}

ostream&operator <<(ostream&os,const CComplex&z)

{

if(fabs(z._x)>err)

cout<<z._x;

if(fabs(z._y-1)<err)

cout<<(fabs(z._x)>err?"+i":"i");

else if(fabs(z._y+1)<err)

cout<<"-i";

else if(z._y >err)

cout<<(fabs(z._x)>err?"+":"")<<z._y<<" i";

else if(z._y<-err)

cout<<z._y<<" i";

return os;

}

istream&operator >>(istream&is,CComplex&z)

{

is>>z._x>>z._y;

return is;

}

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值