【C++】 複數類操作

複數的概念我們高中已經接觸過,包含是實部和虛部,

For example:2i + 3J;實部和虛部值可爲整型,亦可浮點型,那在此實現一下簡單的複數類的操作


代碼如下:

class Complex
{
public:

    Complex(double real,double imag)
    {
        _real = real;
        _imag = imag;
    }

    Complex(const Complex& c)
    {
        _real = c._real;
        _imag = c._imag;
    }

    ~Complex()
    {
        
    }
    
    Complex& operator=(const Complex& c)
    {
        if(&c != this)
        {
        this->_real = c._real;
        this->_imag = c._imag;
        }
        return *this;
    }
    
    Complex operator+(const Complex& c)
    {
        Complex ret(*this);// + 運算返回運算後的值

        ret._real += c._real;
        ret._imag += c._imag;
        
        return ret;
    }

    Complex& operator++() // 前置++ , 當外面需要此返回值時,需要加&
    {
        this->_real += 1;
        this->_imag += 1;

        return *this;
    }

    Complex operator++(int) // 後置++ ,當外面不需要此返回值時,無需加&
    {
        Complex tmp(*this);//後置++返回原來的值,故定義一個臨時變量保存起來

        this->_real += 1;
        this->_imag += 1;

        return tmp;
    }

    
    Complex& operator+= (const Complex& c)
    {
        this->_real = this->_real + c._real;
        this->_imag = this->_imag + c._imag;

        return *this;
    }

    inline bool operator==(const Complex& c)
    {
        return (_real == c._real 
                && _imag == c._imag);
    }

    inline bool operator>(const Complex& c)
    {
        return (_real > c._real
                && _imag > c._imag);
    }

    inline bool operator>=(const Complex& c)
    {
        
        //return (_real >= c._real
        //        && _imag >= c._imag);

        return (*this > c) || (*this == c);//直接使用上面實現重載符 > 和 ==

    }

    inline bool operator<=(const Complex& c)
    {
        //return (_real <= c._real
        //        && _imag <= c._imag);

        return !(*this > c);//直接使用上面實現重載符 > 
    
    }

    bool operator<(const Complex& c)
    {
        return !(*this > c) || (*this == c);//直接使用上面實現重載符 >= 
    }

    inline void Display()
    {
        cout<<_real<<"-"<<_imag<<endl;
    }

private:

    double _real;
    double _imag;

};


測試單元:(偷懶就在main函數裏測試,可以單獨封裝一個函數進行測試)

int main()
{
    Complex c(1,2);
    Complex c1(c);

    //c1.Display();
    //Complex ret = ++c1;
    //Complex ret = c1++;
    //ret.Display();
    Complex ret(c1);
    ret.Display();

    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章