Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First: the two different ways are really "overload as a member" and "overload as a non-member", and the latter has two different ways to write it (as-friend-inside class definition and outside class definition). Calling them "inside class" and "outside class" is going to confuse you.</p> <hr> <p>Overloads for +=, +, -=, -, etc. have a special pattern:</p> <pre><code>struct Vector2 { float x, y; Vector2&amp; operator+=(Vector2 const&amp; other) { x += other.x; y += other.y; return *this; } Vector2&amp; operator-=(Vector2 const&amp; other) { x -= other.x; y -= other.y; return *this; } }; Vector2 operator+(Vector2 a, Vector2 const&amp; b) { // note 'a' is passed by value and thus copied a += b; return a; } Vector2 operator-(Vector2 a, Vector2 const&amp; b) { return a -= b; } // compact </code></pre> <p>This pattern allows the conversions mentioned in the other answers for the LHS argument while simplifying the implementation considerably. (Either member or non-member allows conversions for the RHS when it's passed either as a <code>const&amp;</code> or by value, as it should be.) Of course, this only applies when you do actually want to overload both += and +, -= and -, etc., but that is still common.</p> <hr> <p>Additionally, you sometimes want to declare your non-member op+, etc. as <a href="http://codepad.org/ACNeZcCf" rel="noreferrer">friends</a> within the class definition using the <a href="http://en.wikipedia.org/wiki/Barton-Nackman_trick" rel="noreferrer">Barton-Nackman trick</a>, because due to quirks of templates and overloading, it may not be found <a href="http://codepad.org/3jbvxRN9" rel="noreferrer">otherwise</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload