码迷,mamicode.com
首页 > 其他好文 > 详细

复数类

时间:2015-09-20 07:04:37      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:复数类

#include<iostream>

using namespace std;

class Complex

{

public:

// 带缺省值的构造函数

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

:_real(real)

, _image(image)

{

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

}


// 析构函数

~Complex()

{

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

}


// 拷贝构造函数

Complex(const Complex& d)

:_image(d._image)

, _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->_image = d._image;

}


return *this;

}


void Display()

{

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

}


public:

Complex& operator++()

{

this->_real++;

this->_image++;


return *this;

}


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

{

Complex tmp(*this);


this->_real++;

this->_image++;

return tmp;

}


Complex& operator--()

{

this->_real--;

this->_image--;


return *this;

}

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

{

Complex tmp(*this);


this->_real--;

this->_image--;

return tmp;

}


Complex operator+(const Complex& c)

{

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

}

Complex operator-(const Complex& c)

{

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

}


Complex operator-=(const Complex& c)

{

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

}

Complex operator+=(const Complex& c)

{

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

}


Complex operator*(const Complex& c)

{

Complex tmp(*this);

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

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

return tmp;

}

Complex operator/(const Complex& c)

{

Complex tmp(*this);

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

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

return tmp;

}


private:

double _real;

double _image;

};

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;

}


复数类

标签:复数类

原文地址:http://10622551.blog.51cto.com/10612551/1696419

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!