重载必须返回对对象的引用的运算符

Overloading an operator that must return a reference to an object

本文关键字:引用 运算符 对象 返回 重载      更新时间:2023-10-16
class LongInt
{
public: LongInt& operator++(); //returning a reference
}
LongInt LongInt::operator++()
{
    ...
    LongInt d;

    d.setVector(temp);



    return d; //returning a reference to an object that will be wiped out because it is out of scope
}

我在这里有点困惑。我显然必须通过引用返回以重载增量运算符,但我认为这甚至是不可能的。我遇到内存错误,因为我的指针指向的对象消失了。那么我应该如何重载++运算符呢?

修改对象本身,然后返回*this