c++ - Why overloading of += never return nothing in other people's code? -
let's have simple class
class c { private: int _a; int _b; public: c (int a, int b) :_a { }, _b { b } {} int () { return _a; } int b () { return _b; } bool operator== (c c) { return this->_a == c.a() && this->_b == c.b(); } };
and want overload operator +=
such that
c foo(8, 42); c bar(1, 1); c zoo(9, 43); foo += bar; assert(foo == zoo);
runs fine.
as far i've read other people code, should write like
c operator+= (c c) { return { this->_a += c.a(), this->_b += c.b() }; }
but understanding, return
ing useless. indeed, assertion above not fail when overload +=
as
void operator+= (c c) { this->_a += c.a(); this->_b += c.b(); }
or
c operator+= (c c) { this->_a += c.a(); this->_b += c.b(); return c(0,0); }
tl;dr: why shouldn't return void when overloading +=
?
returning left-hand side of expression allows chain operators, or use result of assignment in single line, i.e.
int c = += b;//this ugly :'(
or
if(a+=b) { }
also, behaviour have on built-in types (paragraph 13.6 of c++ standard), idea mimic custom clases
Comments
Post a Comment