C + + Learning Note (5)----overloaded auto-decrement operator

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.