简体   繁体   English

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

[英]Overloading an operator that must return a reference to an object

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

}

I am kinda confused here. 我在这里有点困惑。 I apparently have to return by reference to overload the increment operator, but I don't think that's even possible. 我显然必须通过引用返回重载增量运算符,但我认为这甚至不可能。 I get a memory fault, because the object my pointer is pointing to disappears. 我得到一个内存错误,因为我的指针指向的对象消失了。 So how should I overload the ++ operator? 那么我应该如何重载++运算符?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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