开发者

Overload += operator if + is overloaded? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Overloading += in c++

Do I need to overload the += operator if I overload + 开发者_如何转开发or will the compiler know what to do?

Thanks.


You need to overload both.

However, if you reverse the order you can reuse your code:

struct foo
{
    // this is the "core" operation, because it's mutating (changes this)
    foo& operator+=(const foo&)
    {
        // ...
        return *this;
    }

};

foo operator+(const foo& lhs, const foo& rhs)
{
    foo ret = lhs;
    ret += rhs;        
    return ret;
}

You make a copy, operate on that copy, and return it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜