Preliminary C + + operator overloading Learning notes <1>Preliminary Discussion on C + + operator overloading Learning notes <2> overloading as friend functions
Increment, decrement operator + + (--) has two forms: former self-increment ++i (self-subtraction). After self-increment i++ (self-reducing i--)
So when we overload the operator, we overload the corresponding form of the operators.
T & operator + + ()//front self-increment ++i
T & operator + + (int)//after self-increment i++
Example:
#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); Think about returning why not 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++ () //Pre-increment ++i{ re = re + 1; return *this;} complex& complex::operator++ (int) //After self-increment i++ int is just the distinction between pre-and post-increment { im = im + 1; return *this;} int main () { complex A (); 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;}
The result output is:
After C self-increment two times imaginary part from 6 to 8
D two times since the real part from 10 to 12
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Preliminary C + + operator overloading Learning notes <3> Increment decrement operator overloading