Preliminary C + + operator overloading Learning notes <3> Increment decrement operator overloading

Source: Internet
Author: User

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 &lt;3&gt; Increment decrement operator overloading

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.