The self-increment operator "+ +" and the decrement operator "--" contain two versions respectively. That is, operator pre-form (such as ++x) and operator post-form (such as x + +), the two operations are not the same. Therefore, when we overload these two operators, we must differentiate between pre-and post-form. C + + distinguishes between pre-and post-forms based on the number of parameters. If you follow the usual method of overloading the + + operator (that is, as a member function overload without parameters, or as a non-member function overload with one argument), then the predecessor version is overloaded. To overload a post form, X + + or x--, you must add an int type parameter to the overloaded function. This parameter is used only to tell the compiler that this is an operator post-form and does not need to give actual parameter values when actually called.
Example, defines an Integer class that overloads the Pre + and post + + operators:
#include <iostream>using namespacestd;classInteger { Public: Integer (intnum) {Value=num; } integer () {Integer (0); } Friend Ostream&operator<< (ostream& OS, integer&integer); Integer&operator++()//front-facing form { This->value++; return* This; } ConstIntegeroperator++(int)//rear-facing form{Integer tmp ( This-value); This->value++; returntmp; } intGetValue ()Const; intSetValue (intnum);Private: intvalue;};intInteger::getvalue ()Const{ returnvalue;}intInteger::setvalue (intnum) {Value=num; returnvalue;} Ostream&operator<< (ostream& OS, integer&integer) {OS<<Integer.value; returnos;}intMainintargcChar*argv[]) {Integer num (Ten); cout<<"num="<< Num <<Endl; Auto Value= num++; cout<<"num++="<< value <<Endl; cout<<"Now num="<< Num <<Endl; Value= ++num; cout<<"++num="<< value <<Endl; return 0;}
The results of the operation are as follows:
S:\debug>string. Exenum=tennum++=nownum= ++num=value=
C + + Learning Note (5)----overloaded auto-decrement operator