重载后增量运算符

nam*_*123 5 c++

MyClass MyClass::operator++(int) {
    return ++(*this);
}
Run Code Online (Sandbox Code Playgroud)

那是我写的代码.我工作正常,但所有教程都说我必须创建一个临时对象并返回它:

MyClass MyClass::operator++(int) {
    MyClass tmp = *this;
    ++(*this);
    return tmp;
}
Run Code Online (Sandbox Code Playgroud)

请告诉我哪种方式最好?

Chr*_*ung 6

第一个版本是错误的,因为它返回新值.postincrement运算符应该返回旧值.


Alo*_*ave 5

第二个!Post Increment意味着在计算表达式后变量会递增.

简单的例子:

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

cout<<j; //j = 10
cout<<i; // i = 11
Run Code Online (Sandbox Code Playgroud)

你的第一个例子是j = 11,这是不正确的.