【C++】複數類的實現

#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;
}

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