复数类Complex

#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;






class Complex
{
friend ostream& operator<<(ostream& _cout, const Complex& c);
public:


Complex(double r = 1.0, double i = 0.0)
: _real(r)
, _image(i)
{}
Complex operator+(const Complex&c)
{
return Complex(_real + c._real, _image + c._image);
}
Complex operator-(const Complex&c)
{
return Complex(_real - c._real, _image - c._image);
}


Complex operator*(const Complex&c)
{

return Complex(_real * c._real - _image*c._image, _image*c._real + _real*c._image);
}


Complex operator/(const Complex&c)
{
double m = c._real*c._real + c._image*c._image;
assert(m != 0);
_real = (_real*c._real + _image*c._image)/(c._real*c._real + c._image*c._image);
_image = (_image*c._real - _real*c._image)/(c._real*c._real + c._image*c._image);
return *this;
}
Complex& operator=(const Complex&c)//返回引用:Complex c3 = c2 = c1;连续赋值,如果返回值,则不能进行下一次赋值,c3.operator=(&c2.operator=(&c1))
{
if(this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
bool operator==(const Complex&c )
{
if(_real == c._real && _image == c._image )
return true;
else
return false;
}


double cab(Complex c)//求复数绝对值(模)
{
double d;
d = sqrt(c._real*c._real+c._image*c._image);
return d;
}
    Complex sqr(Complex c)//求复数平方根
{
_real=sqrt( (cab(c)+c._real)/2 );
_image=sqrt( (cab(c)-c._real)/2 );
return *this;
}
friend istream& operator>>(istream& _cin, Complex& c);

private:
double _real;
double _image;
};


ostream& operator<<(ostream& _cout, const Complex& c)
{
if(c._image == 0)
_cout<<c._real;
else
_cout<<c._real<<"+"<<c._image<<"i";
return _cout;
}


istream& operator>>(istream& _cin, Complex& c)
{
_cin>>c._real>>c._image;
return _cin;
}


void FunTest()
{
//Complex c1(1.0, 2.0);
//Complex c2(1.0, 2.0);
//Complex c3 = c2 = c1;
//Complex c3 = c2/c1;
//bool r = c1.operator==(c2);
Complex c1;
cin>>c1;
cout<<c1<<endl;


}


int main()
{
FunTest();
system("pause");
return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值