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.
If you need reassuring that friend functions can be OK:
http://www.gotw.ca/gotw/084.htm
You are in the “operations needing conversions on the left-hand arguments” camp. If you don’t want a friend, and assuming you have a non-explicit
floatconstructor forFixed, you can implement it as:then implement
minusas a public member function, that most users won’t bother with because they prefer the operator.I assume if you have
operator-(float)then you haveoperator+(float), so if you don’t have the conversion operator, you could go with:Or just
Fixed(lhs) - rhsif you have an explicitfloatconstructor. Those may or may not be as efficient as your friend implementation.Unfortunately the language is not going to bend over backwards to accommodate those who happen to loathe one of its keywords, so operators can’t be static member functions and get the effects of friendship that way ;-p