码迷,mamicode.com
首页 > 编程语言 > 详细

【C++】复数类的实现

时间:2015-08-25 21:33:34      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

#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++】复数类的实现

标签:

原文地址:http://blog.csdn.net/liuxiaoqian_/article/details/47984061

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