If all parameters require type conversion, use the Non-member function for this
We went straight to the subject
If you define a rational number class as follows
class Rational{public: Rational(int numerator=0int denominator=1);//非explicit,允许隐式转换 constoperator*(const Rational& rhs); .......................};result=oneHalf*2;//正确,相当于oneHalf.operator*(2);result=2*oneHalf;//错误,相当于2.operator*(oneHalf);
We can see result=2*oneHalf;
that this sentence cannot be compiled because the compiler does not find much such a function. Then why does result=oneHalf*2;
this sentence get compiled? This is because the class rational at this time can be implicitly converted.
To be able to execute result=2*oneHalf;
this sentence, we can define a non-member function, as follows
constoperator*(constconst Rational& rhs);result=oneHalf*2;//正确,相当于operator*(oneHalf,Rational temp(2));result=2*oneHalf;//正确,相当于operator*(Rational temp(2),oneHalf);
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Effective C + + clause 24