Overload += operator if + is overloaded? [duplicate]
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.
精彩评论