class MyClass
{
// stuff
MyClass operator + (const MyClass& other) const
{ // member func, so '*this' is on the left of the +
f += other.f;
return *this;
}
MyClass operator + (int other) const
{
f += other;
return *this;
} // repeat this for float, or whatever. Or possibly even template it
};
// global funcs to put 'MyClass' on the right of the +, with something else
// on the left
// these don't need to be friends, really, as long as you stick to public
// stuff like ctors and the member versions of +
static MyClass operator + (int l,const MyClass& r)
{
return MyClass(l)+r;
} // again, repeat with other types, or template
@jhrode: Be aware that your operator+ is very non-intuitive.
In the code:
int a = 5;
int b = 4;
int x = a + b;
x is assigned 9 by the third statement and a and b are unchanged.
In your operator+ above, you are actually modifying a such that
both x and a would contain 9.
Thanks guys - makes sense. Yeah, I realize the + operator was illogical - I think I must have had the "chaining" notion still stuck in my head, as in the assignment operator. Just a mistake of typing it out too quickly.