(a)
if a class. It seems reasonable to agree that integers are "implicitly converted to" rational numbers.
Class rational{Public: Rational (int numerator = 0, int denominator = 1);//deliberately not for explicit; consent int-to-rational implicit conversion int numerator () const; int denominator () const; };
Consider whether the member function, or the Non-member function, is implemented when arithmetic operators are supported:
(1) The notation of the member function:
Class rational{public: Const Rational operator* (const rational& RHS) const;}; Rational oneeight (1,8); Rational onehalf; Rational result = Onehalf * oneeight; Niceresult = result * Oneeight; Ok
but you want to support hybrid operations:
result = Onehalf * 2; OK 2 An implicit type conversion has occurred.result = 2 * onehalf; Wrong!!!
The compiler converts the above statement to the following statement:
result = onehalf.operator* (2); Okresult = 2.operator* (onehalf); wrong!
Onehalf is an object of class with a operator* function. However, 2 does not have a corresponding class, and the compiler will attempt to find Non-member operator* (that is, within the namespace or global scope) that can be called as follows:
result = operator* (2, onehalf);//wrong!
In this case, there is no such a non-member operator* that accepts int and rational as a parameter, so the lookup fails.
there is only whenthe parameters are listed in the parameter list, which is the qualified participant for the implicit type conversion.。
status equals "The object to which the member function is called"-that is, the metaphorical reference of this object, which is by no means a qualified participant of the implicit conversion .
(ii) Ways to address such problems:
To support mixed operations. Let operator* become a non-member function. It is agreed that the compiler will run an implicit type conversion on each of the arguments:
Const Rational operator* (const rational& LHS, const rational& RHS) { return rational (lhs.numerator () * rhs.nu Merator (), Lhs.denominator () * Rhs.denominator ()); }result = 2 * onehalf;//ok. The final compilation passed!
does operator* want to be a friend function of rational? The answer is in the negative. Because the operator* complete the task by rational public interface;
Whenever you assume that you can avoid the friend function, you should avoid it.
Please remember:
Suppose you need a type conversion for all the parameters of a function that contains the metaphor reference referred to by this pointer, then this function must be a non-member.
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
Effective C + +: Regulation 24: If all units require parameter type conversion, use do this non-member function