【C++】复数类

来源:互联网 发布:js中get post 区别 编辑:程序博客网 时间:2024/05/17 09:06
#include<iostream>using namespace std;class Complex{public:void Display(){cout<<"Real:"<<_real<<"Image:"<<_image<<endl;}// 带缺省值的构造函数Complex (double real = 0.0, double image = 0.0):_real(real),_image(image){//初始化列表cout<<"Complex (double real = 0.0, double image = 0.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;}Complex operator +(Complex& c)//声明成员函数重载运算符"+"{cout<<"operator +(Complex& c)"<<endl;Complex temp;temp._real  = this->_real + c._real;temp._image = this->_image + c._image;return temp;}Complex operator -(Complex& c){cout<<"operator -(Complex& c)"<<endl;Complex temp;temp._real  = this->_real - c._real;temp._image = this->_image - c._image;return temp;}Complex operator *(Complex& c){cout<<"operator *(Complex& c)"<<endl;Complex temp;temp._real = this->_real*c._real - this->_image * c._image;temp._image = this->_real *c._image + this->_image * c._real;return temp;}Complex operator /(Complex& c){cout<<"operator -(Complex& c)"<<endl;Complex temp;temp._real = (this->_real*c._real + this->_image * c._image)/(c._real*c._real + c._image * c._image);temp._image = (this->_image * c._real -this->_real *c._image)/(c._real*c._real + c._image * c._image);return temp;}Complex& operator++()//前置++{this->_real++;return *this;}Complex operator++(int) //后置++{Complex temp(*this);this->_real++;return temp;}Complex& operator--()//前置--{this->_real--;return *this;}Complex operator--(int) //后置--{Complex temp(*this);this->_real--;return temp;}Complex& operator-=(const Complex& c){this->_real -= c._real;this->_image -= c._image;return *this;}Complex& operator+=(const Complex& c){this->_real += c._real; //(this->_real = this->_real + c._real)this->_image += c._image;return *this;}private:double _real;double _image;};void TestComplex (){Complex c1(2.2, 1.1);Complex c2 = c1++;c1.Display();c2.Display();}int main(){Complex c1(2.2,1.1);c1.Display ();Complex c2(c1);//调用拷贝构造函数c2.Display();Complex c3;//赋值运算符的重载c3 = c2;c3.Display();Complex c4 = c1 + c2;c4.Display();Complex c5 = c3 - c2;c5.Display();Complex c6 = c3 * c2;c6.Display();Complex c7(c1);c7++;c7.Display();Complex c8;c8 += c1;c8.Display();getchar();return 0;}

0 0
原创粉丝点击