Why am I allowed to overload + in the aboce case, but no in the following case where I am using a non-member function?
If perhaps you did this:
Code:
void operator + (test *a)
{
a->x += x;
}
Then the x's are added and the answer is stored in a, which is not necessarily what you want as
c = a + b;
is expected to work. Your operator is void, so we cannot depend on that.
If you wanted to go non-member non-friend then
Code:
const test & operator + (const test &a, const test &b)
{
return test(a.getX() + b.getX());
}
is the binary + operator.
So the answers to your question include because your original operator has no return value, and because even if you wrote an operator outside, it needs access to the member x. There are many ways to safely access x, including accessor methods, or through use of the friend keyword. You could also make x public and not write an accessor, but then you will have to make sure not to use x inappropriately.