Operator overload after increment

MyClass MyClass::operator++(int) {
    return ++(*this);
}

This is the code I wrote. I am working correctly, but all the tutorials say that I should create a temporary object and return it:

MyClass MyClass::operator++(int) {
    MyClass tmp = *this;
    ++(*this);
    return tmp;
}

Please tell me which way is better?

+5
source share
4 answers

Second! Post Increment means that the variable increases as the expression evaluates.

A simple example:

int i = 10;
int j = i++;

cout<<j; //j = 10
cout<<i; // i = 11

Your first example will do j = 11what is wrong.

+5
source

The first version is incorrect because it returns a new value. The postincrement statement should return the old value.

+6
source

.

. post-increment , . int:

int x = 5;
int y = x++;
cout << x << y << endl; // prints 56, not 66.
+2
source

This is due to the definition of the post-increment statement.

post-increment operator : increases as you use it.

Operator

pre-increment : incremented before the value is used.

So, if you do it your own way, the value returned by the function is incremental.

The textbooks enlarge the object itself, but return the non-increased COPY of the object.

0
source

All Articles