quote:Original post by Anonymous Poster
you can make the binary + a member function, just only have one parameter.
I looked that up, and he''s right. Thanks!
quote:However it is considered better form to have it be a non member function and implement it in terms of +=. That way it lets implicit constuctors work on the left operand
I think it''s a bad idea to implement operator+ in terms of operator+=, because a + normally takes its lhs and rhs operands, adds them together and returns the sum without modifying either of them. If you''re speaking of using operator+= on the sum object, well isn''t that inefficient? Consider:
// using += on one of the operands:myclass &operator+(myclass &m1, myclass &m2){ m1 += m2; return m1;}// this has the effect of making c = a + b set c to the sum, but// a to the sum as well.//// using += on the sum object:myclass &operator+(myclass &m1, myclass &m2){ myclass m; m += m1; m += m2; return m;}// this is just plain stoopid.//// what I consider to be the best way for pseudo-arithmetic types:myclass &operator+(myclass &m1, myclass &m2){ mylcass m; m = m1 + m2; // this would actually be a + on the individual fields, // such as the coordinates in a vector return m;}// c = a + b behaves properly.
Alternatively, as a member function:
myclass &myclass::operator+(myclass &m){ myclass r = *this; r += m; return r; // 2 assignments, an extra copy of r and one addition. // compare to one copy of the sum, one addition and one assignment for friend version}