简体   繁体   中英

C++ overloading increment operator

I have a header file which has a date class defined with month day and year variables and overloaded increment method:

mydate operator++(int) {
    return mydate(m, d+1, y);
}

and the main cpp has the header included, so once I run cout<<dateXY++; it shows me the date incremented by one, however, it doesn't keep the value of the object, but rather resets it to original. So if i put cout<<dateXY; after the increment, it will show the original date.

Can I modify the operator overloading so that object keeps the value?

Assuming this function is a member function of the mydate class (wouldn't make much sense otherwise), you need to create a temporary instance of mydate with the old value, increase the value of this and return the temporary instance.

Like

mydate operator++(int) {
    mydate tmp(m, d, y);
    // set date to date + 1
    return tmp;
}

It's how the post-increment operator works, it increments the value but returns the old value before the increment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM