Operator implementation * 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)

This was mentioned by scott meyers in Effective C ++, as shown below.

Even when the Rationl constructor is not explicit, one compiles and one does not. The reason is listed below:

It turns out that the parameters have the right to implicit conversion "only if they are listed in the parameter list."

The implicit parameter corresponding to the object on which the member function is called - one "this" indicates - never have the right to implicit conversions. Thus, the first call compiles, and the second does not.

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

+3
source share
3 answers

, .

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

int , , oneHalf, , . " " . .

+5

, , -, *this , .

0

, ", "? ?

, (-):

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

,

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)
0

Source: https://habr.com/ru/post/1787110/


All Articles