標籤:
#include<iostream>using namespace std;class Complex{private: double _real; double _image;public: Complex(double real = 2.2,double image=1.1)//建構函式 { cout<<"建構函式被調用"<<endl; _real = real; _image = image; } Complex(const Complex& d)//拷貝建構函式 { cout<<"拷貝建構函式被調用"<<endl; this->_real = d._real ; this->_image = d._image ; } ~Complex() { cout<<"解構函式被調用"<<endl; } void Display() { cout<<"Real:"<<_real; cout<<" Image:"<<_image<<endl; }public: Complex& operator=(const Complex& d) { if(this != &d) { cout<<"賦值運算子被重載"<<endl; this->_real = d._real ; this->_image = d._image ; } return *this; } Complex& operator++() { cout<<"前置++被重載"<<endl; this->_real++; return *this; } Complex operator++(int) { cout<<"後置++被重載"<<endl; Complex *tmp = this; this->_real++; return *tmp; } Complex& operator--() { cout<<"前置--被重載"<<endl; this->_real --; return *this; } Complex operator--(int) { cout<<"後置--被重載"<<endl; Complex *tmp = this; this->_real --; return *tmp; } Complex operator+(const Complex& d) { cout<<"+被重載"<<endl; Complex tmp ; tmp._real = this->_real + d._real ; tmp._image = this->_image + d._image ; return tmp; } Complex operator-(const Complex& d) { cout<<"-被重載"<<endl; Complex tmp; tmp._real = this->_real - d._real ; tmp._image = this->_image - d._image; return tmp; } Complex& operator-=(const Complex& d) { cout<<"-=被重載"<<endl; this->_real -= d._real ; this->_image -= d._image ; return *this; } Complex& operator+=(const Complex& d) { cout<<"+=被重載"<<endl; this->_real += d._real ; this->_image += d._image ; return *this; } Complex operator*(const Complex& d) { Complex tmp; tmp._real = this->_real * d._real - this->_image * d._image; tmp._image = this->_image * d._real + this->_real * d._image; return tmp; } Complex operator/(const Complex& d) { Complex tmp; tmp._real = (this->_real * d._real + this->_image * d._image)/ (d._real * d._real +d._image * d._image); tmp._image = (this->_image * d._real - this->_real * d._image)/ (d._real * d._real +d._image * d._image); return tmp; }}; int main(){ Complex d1; d1.Display(); //Complex d2(d1); Complex d2 = d1; d2.Display(); Complex d3(4.4,5.5); d3.Display() ; d3 = d2; d3.Display(); ++d3; d3.Display (); d3++; d3.Display (); --d3; d3.Display (); d3--; d3.Display (); //system(pause); d3 = d3+d1; d3.Display (); d3 = d3-d1; d3.Display (); d3-=d1; d3.Display (); getchar(); return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【C++】複數類的實現