C++复数类的完成

#include <iostream>

using namespace std;

class Complex
{
public:
    Complex(double r, double i);
    Complex operator + (const Complex &c);
    Complex operator - (const Complex &c);
    Complex operator * (const Complex &c);
    Complex operator / (const Complex &c);
    Complex operator += (const Complex &c);
    Complex operator -= (const Complex &c);
    Complex operator *= (const Complex &c);
    Complex operator /= (const Complex &c);

    bool operator == (const Complex &c);
    void print(Complex &c);
private:
    double _real;
    double _image;
};

Complex::Complex(double r = 0.0, double i = 0.0)
{
    _real = r;
    _image = i;
}

//两复数相加  
Complex Complex::operator + (const Complex &c)
{
    Complex tmp;
    tmp._real = _real + c._image;
    tmp._image = _image + c._image;
    return tmp;
}

//两复数相减
Complex Complex::operator - (const Complex &c)
{
    Complex tmp;
    tmp._image = _image - c._image;
    tmp._real = _real - c._real;
    return tmp;
}

//两复数相乘
Complex Complex::operator*(const Complex &c)
{
    Complex tmp;
    tmp._image = _image* c._image;
    tmp._real = _real* c._real;
    return tmp;
}

//两复数相除
Complex Complex::operator / (const Complex &c)
{
    Complex tmp;
    tmp._real = _real / c._real;
    tmp._image = _image / c._image;
    return tmp;
}
//加等
Complex Complex::operator += (const Complex &c)
{
    this->_real += c._real;
    this->_image += c._image;
    return *this;
}

//减等
Complex Complex::operator -= (const Complex &c)
{
    this->_image -= c._image;
    this->_real -= c._real;
    return *this;

}
//乘等
Complex Complex::operator *= (const Complex &c)
{
    this->_image *= c._image;
    this->_real *= c._real;
    return *this;
}

Complex Complex::operator /= (const Complex &c)
{
    this->_image /= c._image;
    this->_real /= c._real;
    return *this;
}

bool Complex::operator == (const Complex &c)
{
    return (this->_image == c._image) && (this->_real == c._real);
}

void Complex::print(Complex &c)
{
    cout << c._real << "+ " << c._image << "i" << endl;
}
void Test1()
{
    Complex c1(1.0, 2.0), c2(2.0, 1.0);
    //Complex c3 = c1 -= c2;
    //Complex c3=c1 += c2;
    //Complex c3 = c1 + c2;
    Complex c3 = c1 *= c2;
    //Complex c3=c1-c2;
    cout << (c1 == c2) << endl;
    c1.print(c1);
    c3.print(c3);

}


int main()
{
    Test1();
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值