天天看点

013--C++养成之路(运算符重载:前++,后++)

笔记:使用成员函数重载,实现前++,后++
#include<iostream>
using namespace std;
//运算符重载
//实现两个复数相加
//编译器不知道+=自定义运算规则,你要自己去重载一个函数来实现这个规则。
class Complex{
private:
  int m_real;
  int m_vir;
  friend Complex operator+(const Complex& cp1,const Complex& cp2);
public:
  Complex(){}
  Complex(int real,int vir):m_real(real),m_vir(vir){
  
  }
  //前++
  Complex& operator++(){//Complex不加引用&是返回本身
    this->m_real++;
    this->m_vir++;
    return *this;
  }
  //后++   加引用返回对象,不加引用返回对象的值
  Complex operator++(int){
    Complex temp;
    temp=*this;
    this->m_real++;
    this->m_vir++;
    return temp;
  }
  /*
  Complex operator++(int){
    Complex temp;
    temp=*this;
    ++(*this);//对象自增
    return temp;//返回自增之前的值
  }*/
  void print(){
  cout<<m_real<<"+"<<m_vir<<"i"<<endl;
  }
  ~Complex(){
  
  }
};

int main(){
  Complex c1(1,3);
  c1.print();
  (++c1).print();//前++
  cout<<"=========================="<<endl;
  Complex c2(1,1);
  c2.print();
  (c2++).print();//后++
  return 0;
}