c++ - Defining a proper subtraction operator -


I wrote an abstract class for a math object, and defined all operators. When using it, I came across:

Fixed F1 = 5.0 F - F3;

I have only definition of two subtraction operators:

  inline conic fixed operator - () cons; Inline conic fixed operator - (float F) console;  

What's wrong with me here - the additional is swapable (1 + 2 == 2 + 1) while there is no subtraction (this also goes for multiplication and division). I immediately wrote a class outside in this way:

  Fixed inline static operator - (float F, CONST fixed and FP);  

But then I realized that this can not be done, because for doing so I have to touch the class personal, which is to use the keyword friend As a result of I, the namespace is polluted with 'stable' redundant function.

Error: 'Fixed Constraints Fixed Fixed: Operator- (Float, Constant & Fixed; Amp;) 'should either be a non-static member function or non-member function.

According to the suggestions suggested by GCC, a non-static task is the result of the following error:

  Error: 'Fixed Fixed Fixed :: Operator- (Float, Constant & amp; nbsp;) should take zero or one argument  

Why can not I define the same operator within the class definition? If there is no way to do this, then is not anyone using the friend keywords anyway?

The same question goes for division, because it suffers from the same problem.

If you have to be confident that friend work may be fine:

Which operations require access to internal data, will we have to donate through friendship? These should generally be members. (There are some rare exceptions, such as operations that require conversion on the arguments of their left hand, and some such operators like & lt; & lt; () whose signatures * do not allow these references to their first parameters; In terms of non-friends (potentially virtual) members' conditions, but sometimes it is only a practice in contortionism and they are expressing as best and naturally friends )

If you do not want a friend, and assuming that you have float constructor < Code> Fixed , you can apply it to:

  Fixed inline fixed operator- (cost-fixed & LHS, tight fixed & amp; rhs) {return L.H. Aminus (RAS); }  

Then implement zero as a public subscriber function, that most users will not bother because they prefer operators.

I assume that you have operator- (float) , then you have operator + (float) , so if you have a conversion operator If not, you can go with it:

  Fixed inline fixed operator - (float LHS, CONST fixed & RA) {return (-RHS) + LHS; // Return (-RHS) - (- LHS); If any operator + ...}  

or just Fixed (LHS) - rhs if you have a clear float constructor May be or be in the form of the implementation of your friend.

Unfortunately the language is not going to tilt backwards to accommodate those who hate in their keywords, so the operator can not be a stable member and thus the effect of friendship get; -P


Comments