增量、减量运算符++(--)分别有两种形式:前自增++i(自减--i),后自增i++(自减i--)
因此当我们重载该运算符时,要重载相应形式的运算符。
T & operator ++() // 前自增++i
T & operator ++(int) //后自增 i++
举例:
#include <iostream> using namespace std; class complex { double re; double im; public: complex(double _re,double _im):re(_re),im(_im){}; void print(){cout<<re<<" "<<im<<endl;} friend complex operator+(const complex &a ,const complex &b); //想想返回为什么不是complex & complex& operator++(); complex& operator++(int); }; complex operator+(const complex &a , const complex &b) { return complex(a.re + b.re , a.im + b.im ); } complex& complex::operator++() //前自增 ++i { re = re + 1; return *this; } complex& complex::operator++(int) //后自增 i++ int只是区分前后自增 { im = im + 1; return *this; } int main() { complex a(1,2); complex b(3,4); complex c = a + b; complex d = a + b + c; c.print(); d.print(); (c++)++; c.print(); ++(++d); d.print(); return 0; }
结果输出为:
c后自增两次 虚部由6到8
d前自增两次 实部从10到12