前++和后++运算符的重载

    技术2022-07-10  150

    #include <cstdio> #include <iostream> #include <cmath> #include <cstring> using namespace std; class Complex { public: Complex(){} Complex(int r, int v):r(r),v(v){} friend ostream& operator<<(ostream& os,const Complex& c); Complex operator+(Complex& c) { int r =this->r +c.r; int v =this->v +c.v; Complex temp(r,v); return temp; } Complex operator++() { this->r++; this->v++; return *this; } Complex operator++(int) { Complex temp(this->r,this->v); this->r++; this->v++; return temp; } private: int r; int v; }; ostream& operator<<(ostream& os,const Complex& c) { int r =c.r; int v =c.v; if(r ==0) { printf("%di", v); } else if(v ==0) { printf("%d", r); } else if( v< 0) { printf("%d%di",r,v); } else { printf("%d+%di",r,v); } return os; } int main()x { Complex c1(1,1); Complex c2(2,2); cout << c1 << endl; cout << c1++ + c2 << endl; cout << ++c1 +c2 << endl; return 0; }

    前++ 实质上是: a =a+1; return a;

    后++实质上是: b =a; a =a+1; return b;

    Processed: 0.011, SQL: 9