I wrote an abstraction class for a math object, and defined all of the operators. While using it, I came across:
Fixed f1 = 5.0f - f3;
I have only two subtraction operators defined:
inline const Fixed operator - () const;
inline const Fixed operator - (float f) const;
I get what is wrong here - addition is swappable (1 + 2 == 2 + 1) while subtraction is not (same goes for multiplication and division). I immediately wrote a function outside my class like this:
static inline const Fixed operator - (float f, const Fixed &fp);
But then I realized this cannot be done, because to do that I would have to touch the class's privates, which results to using the keyword friend
which I loath, as well as polluting the namespace with a 'static' unnecessary function.
Moving the function inside the class definition yields this error in gcc-4.3:
error: ‘static const Fixed Fixed::operator-(float, const Fixed&)’ must be either a non-static member function or a non-member function
Doing as GCC suggested, and making it a non-static function results the following error:
error: ‘const Fixed Fixed::operator-(float, const Fixed&)’ must take either zero or one argument
Why can't I define the same operator inside the class definition? if there's no way to do it, is there anyway else not using the friend
keyword?
Same question goes for division, as it suffers from the same problem.