The self-increment "+ +" and "subtract"--"are unary operators, and both the pre-and post-form can be overloaded. Take a look at the following example:
#include <iostream>#include<iomanip>using namespacestd;classstopwatch{//StopwatchPrivate: intMin//minutes intSec//seconds Public: Stopwatch (): Min (0), SEC (0){ } voidSetzero () {min =0; SEC =0; } Stopwatch run (); //RunStopwatchoperator++();//++i, front-facing formStopwatchoperator++(int);//i++, rear-facing formFriend Ostream &operator<< (Ostream &,ConstStopwatch &);}; Stopwatch Stopwatch::run () {++sec; if(sec = = -) {min++; SEC=0; } return* This;} Stopwatch Stopwatch::operator++(){ returnrun ();} Stopwatch Stopwatch::operator++(intN) {Stopwatch S= * This; Run (); returns;} Ostream&operator<< (Ostream & out,ConstStopwatch &s) { out<<setfill ('0') <<SETW (2) <<s.min<<":"<<SETW (2) <<s.sec; return out;}intMain () {stopwatch S1, S2; S1= s2 + +; cout<<"S1:"<< S1 <<Endl; cout<<"S2:"<< S2 <<Endl; S1.setzero (); S2.setzero (); S1= ++S2; cout<<"S1:"<< S1 <<Endl; cout<<"S2:"<< S2 <<Endl; return 0;}
The above code defines a simple stopwatch class, min for minutes, sec for seconds, setzero () function for stopwatch zeroing, run () function to describe the second hand movement, followed by three operator overloading functions.
Take a look at the implementation of the run () function, and the run () function starts by increasing the second hand, and if the self-increment result equals 60, it should be rounded up, minutes plus 1, and the second hand zeroed.
The operator++ () function implements the self-increment pre-form, returning directly to the run () function result.
The operator++ (int n) function implements the self-increment post form, and the return value is the object itself, but then when the object is used again, the object is self-increasing, so in the function body of the function, the object is saved first, then the run () function is called, and then the previously saved object is returned. In this function the parameter n is meaningless, it exists only to distinguish between a pre-form or a post-form.
The overloads of the decrement operator are similar to the above, and are not described here.
C + + Learning 30 overloaded + + and--(self-increment auto-decrement operator)