简体   繁体   中英

implementing operator * in C++

class Rational {

 const Rational operator*(const Rational& rhs) const

  ...
};

 Rational oneHalf(1,2);

 Rational result = oneHalf * 2;   // fine (with non-explicit ctor)
 result          = 2 * oneHalf;  // error! (even with non-explicit ctor)

It was mentioned by scott meyers in Effective C++ book as below

Even when Rationl's constructor is not explicit, one compiles and one doesnot. Reason is given as below:

It turns out that parameters are eligible for implicit conversion "only if they are listed in the parameter list".

The implicit parameter corresponding to object on which member function is invoked -- the one "this" points to -- is never eligible for implicit conversions. That's way first call compiles and the second one doesnot.

My question is what does author mean in above statment "only if they are listed in the parameter list" ? What is parameter list?

When you write an operator, try to think of it in terms of an explicit function call.

Rational oneHalf(1, 2);
Rational result = oneHalf.multiply(2); // Ok, can convert
Rational result = 2.multiply(oneHalf); // OWAIT, no such function on int.

Since there is no such operator on an int, the compiler doesn't know how to handle oneHalf to make the call work, and throws an error. The "Parameter list" in this case is the argument to the operator. You need to make a free function.

他的意思是函数参数可以被隐式转换,但是对函数形成*this东西永远不会被隐式转换。

My question is what does author mean in above statment "only if they are listed in the parameter list" ? What is parameter list?

What he meant is that the parameter list in your constructor(s):

class Rational
{
  public:
     Rational (int a);  // <-- here 'a'
     Rational (double b); //<-- here 'b'
};

If you've these two constructors in your class, then you can write

Rational result1 = oneHalf * 2; //2 is int, so it converts into Rational(2)
Rational result2 = oneHalf * 2.9; //2.9 is double, so it converts into Rational(2.9)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM