A few comments;
The reason that Stoned_Coder's solution worked (+/- some minor things like adding missing semi-colons) is that he defined operator+ as a member of the class math;
Code:
math operator +(const int added)
{
math temp(*this); // this creates a copy of *this
temp.number += added; // increased temp.number by added ...
return temp; // and return the temporary copy
}
If x and y are both of type math, this code will be called in an example;
which the compiler treats as;
Code:
y = x.operator+(10);
Although it works, I wouldn't define it quite this way; instead of
Code:
class math
{
public:
// constructors, etc
math operator+(const int added);
};
I would recommend this ....
Code:
class math
{
public:
// constructors, etc
math operator+(int added) const;
};
The reason for changing the location of the const keyword is twofold. Firstly, an int passed by value remains constant as far as the caller is concerned. Secondly, const at the end of the declaration tells the compiler that the operation y = x + 10; does not change x.
If you want to work with obj1 = 10 + obj2, and with obj1 = obj2 + 10; you need to provide two forms of operator+(), viz.
Code:
class math
{
public:
// constructors, etc
math operator+(int add) const; // used for y = x + 10
friend math operator+(int value, const math &add); // used for y = 10 + x;
};
math math::operator+(int add) const
{
math temp(*this);
temp.number += add;
return temp;
// alternate implementation if math has a constructor that takes an int argument
// math temp(number + add);
// return temp;
}
math operator+(int value, const math &add)
{
// this assumes math has a constructor that accepts an int argument ....
math temp(value + add.number);
return temp;
}