1. 程式人生 > >C++模擬實現複數類

C++模擬實現複數類

#include <iostream>
using namespace std;

class Complex
{
public:
    Complex(double Real = 0.0f, double Image = 0.0f)
        :_Real(Real)
        ,_Image(Image)
    {}

    Complex(const Complex& c)
        :_Real(c._Real )
        ,_Image(c._Image )
    {}
    ~Complex()
    {}
    Complex& operator
=(const Complex& c) { if(this != &c) { _Real = c._Real ; _Image = c._Image ; } return *this; } Complex operator+(const Complex& c) { return Complex(_Real = _Real + c._Real,_Image = _Image + c._Image); } Complex operator
-(const Complex& c) { return Complex(_Real = _Real - c._Real,_Image = _Image - c._Image); } Complex& operator*(const Complex& c) { return *this *= c; } Complex operator/(const Complex& c) { return *this /= c; } Complex& operator
+=(const Complex& c) { _Real += c._Real ; _Image += c._Image ; return *this; } Complex& operator-=(const Complex& c) { _Real -= c._Real ; _Image -= c._Image ; return *this; } Complex& operator*=(const Complex& c) { _Real = _Real * c._Real - _Image * c._Image; _Image = _Real * c._Image + _Image * c._Real; return *this; } Complex& operator/=(const Complex& c) { _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; } bool operator >(const Complex& c) { if(*this != c) { if((_Real > c._Real) || (_Image > c._Image) ) return 1; } return 0; } bool operator >=(const Complex& c) { if((_Real >= c._Real) || (_Image >= c._Image) ) return 1; } bool operator <(const Complex& c) { if(*this != c) { if((_Real < c._Real) || (_Image < c._Image) ) return 1; } return 0; } bool operator <=(const Complex& c) { if((_Real <= c._Real) || (_Image <= c._Image) ) return 1; } bool operator ==(const Complex& c) { return ((_Real == c._Real) && (_Image == c._Image)); } bool operator !=(const Complex& c) { return ((_Real != c._Real) && (_Image != c._Image)); } friend ostream &operator<<(ostream& output, const Complex &c) { output << c._Real ; if (c._Image > 0) { std::cout << "+"; } std::cout << c._Image << "i"; return output; } private: double _Real; double _Image; }; int main() { //Complex c1(1.0,2.0);//賦值 //Complex c2; //Complex c3; //c2 = c1; //c3 = c2 = c1; //Complex c1(1.0,2.0);//加減法 //Complex c2(2.0,3.0); //Complex ret; //ret = c2 - c1; //cout<<ret; //Complex c1(1.0,2.0);//+=、-= //Complex c2(2.0,3.0); //c2 += c1; //cout<<c2; //c2 -= c1; //cout<<c2; Complex c1(1.0,2.0);//比大小 Complex c2(2.0,3.0); //c1 == c2; if(c1 < c2) { cout<<"ok"; } else { cout<<"no"; } //Complex c1(1.0,2.0); //Complex c2(2.0,3.0); //Complex c3; //c3 = c1 * c2; ////c3 = c1/c2; //cout<<c3; return 0; }

其中加減乘除法那塊還有不足。