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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章