I know I can answer this question easily for myself by generatin the code and see if it compiles. But since I couldn\'t find a similar question, I thought it\'s knowledge worth
The canonical form of implementing operator+()
is a free function based on operator+=()
, which your users will expect when you have +
. +=
changes its left-hand argument and should thus be a member. The +
treats its arguments symmetrically, and should thus be a free function.
Something like this should do:
//Beware, brain-compiled code ahead!
class MyClass {
public:
MyClass& operator+=(const MyClass &rhs) const
{
// code for adding MyClass to MyClass
return *this;
}
MyClass& operator+=(int rhs) const
{
// code for adding int to MyClass
return *this;
}
};
inline MyClass operator+(MyClass lhs, const MyClass& rhs) {
lhs += rhs;
return lhs;
}
inline MyClass operator+(MyClass lhs, int rhs) {
lhs += rhs;
return lhs;
}
// maybe you need this one, too
inline MyClass operator+(int lhs, const MyClass& rhs) {
return rhs + lhs; // addition should be commutative
}
(Note that member functions defined with their class' definition are implicitly inline
. Also note, that within MyClass
, the prefix MyClass::
is either not needed or even wrong.)