简体   繁体   English

在C ++中实现operator *

[英]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 scott meyers在Effective C ++的书中提到了如下

Even when Rationl's constructor is not explicit, one compiles and one doesnot. 即使Rationl的构造函数不明确,一个编译,一个不编译。 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. 与调用成员函数的对象相对应的隐式参数 - “this”指向的对象 - 永远不能进行隐式转换。 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. 由于int上没有这样的运算符,编译器不知道如何处理oneHalf以使调用工作,并抛出错误。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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