MyClass MyClass::operator++(int) {
return ++(*this);
}
That's the code I have written. I works correctly, but all tutorials say that I have to create a temporary object and return it:
MyClass MyClass::operator++(int) {
MyClass tmp = *this;
++(*this);
return tmp;
}
Please tell me which way is the best?
The postfix increment operator ++ can be overloaded for a class type by declaring a nonmember function operator operator++() with two arguments, the first having class type and the second having type int . Alternatively, you can declare a member function operator operator++() with one argument having type int .
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
++i will increment the value of i , and then return the incremented value. i++ will increment the value of i , but return the original value that i held before being incremented.
2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;
The first version is wrong, because it returns the new value. The postincrement operator is supposed to return the old value.
Second One! Post Increment means that the variable is incremented after the expression is evaluated.
Simple example:
int i = 10;
int j = i++;
cout<<j; //j = 10
cout<<i; // i = 11
Your First example would make j = 11
, which is incorrect.
The tutorials are correct.
Your version returns the wrong value. The post-increment operator is supposed to return the previous value, not the new value. Check for yourself with a plain old int:
int x = 5;
int y = x++;
cout << x << y << endl; // prints 56, not 66.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With