複數類

#include<iostream>

using namespace std;

class Complex

{

public:

// 帶缺省值的構造函數

Complex(double real = 0, double p_w_picpath = 0)

:_real(real)

, _p_w_picpath(p_w_picpath)

{

cout << "Complex (double real = 0, double p_w_picpath = 0)" << endl;

}


// 析構函數

~Complex()

{

cout << "~Complex()" << endl;

}


// 拷貝構造函數

Complex(const Complex& d)

:_p_w_picpath(d._p_w_picpath)

, _real(d._real)

{

cout << "Complex (const Complex& d)" << endl;

}


// 賦值運算符重載

Complex& operator= (const Complex& d)

{

cout << "operator= (const Complex& d)" << endl;


if (this != &d)

{

this->_real = d._real;

this->_p_w_picpath = d._p_w_picpath;

}


return *this;

}


void Display()

{

cout << "Real:" << _real << "--Image:" << _p_w_picpath << endl;

}


public:

Complex& operator++()

{

this->_real++;

this->_p_w_picpath++;


return *this;

}


Complex operator++(int) //後置++

{

Complex tmp(*this);


this->_real++;

this->_p_w_picpath++;

return tmp;

}


Complex& operator--()

{

this->_real--;

this->_p_w_picpath--;


return *this;

}

Complex operator--(int) //後置--

{

Complex tmp(*this);


this->_real--;

this->_p_w_picpath--;

return tmp;

}


Complex operator+(const Complex& c)

{

return Complex(this->_real + c._real, this->_p_w_picpath + c._p_w_picpath);

}

Complex operator-(const Complex& c)

{

return Complex(this->_real - c._real, this->_p_w_picpath - c._p_w_picpath);

}


Complex operator-=(const Complex& c)

{

return(_real - c._real, _p_w_picpath - c._p_w_picpath);

}

Complex operator+=(const Complex& c)

{

return(_real + c._real, _p_w_picpath + c._p_w_picpath);

}


Complex operator*(const Complex& c)

{

Complex tmp(*this);

this->_real = _real*c._real - _p_w_picpath*c._p_w_picpath;

this->_p_w_picpath = _real*c._p_w_picpath + _p_w_picpath*c._real;

return tmp;

}

Complex operator/(const Complex& c)

{

Complex tmp(*this);

this->_real = (_real*c._real + _p_w_picpath*c._p_w_picpath) / (c._real*c._real + c._p_w_picpath*c._p_w_picpath);

this->_p_w_picpath = (_p_w_picpath*c._real - _real*c._p_w_picpath) / (c._real*c._real + c._p_w_picpath*c._p_w_picpath);

return tmp;

}


private:

double _real;

double _p_w_picpath;

};

void Test1()

{

Complex d1(1, 2);

Complex d2(2, 3);

d2 = d1;

d1.Display();

d2.Display();

}

void Test2()

{

Complex d1(1, 2);

Complex d2(2, 3);

d1 = d1 - d2;

d1.Display();

d2.Display();


}

int main()

{

//Test1();

Test2();

return 0;

}


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