简体   繁体   English

当我的对象在C ++中位于右侧时,如何重载运算符*?

[英]How do I overload the operator * when my object is on the right side in C++?

I want to implement "operator * " overloading INSIDE my class, so I would be able to do the following: 我想在类的内部实现“ operator *”的重载,因此我可以执行以下操作:

Rational a(1, 2), b;
b = 0.5 * a; // b = 1/4

Notice that b is on the right side, is there a way to do such a thing inside "Rational" class? 注意b在右边,有没有办法 “理性”类中做这样的事情?

No. You must define operator* as a free function. 不可以。您必须将operator*定义为自由函数。 Of course, you could implement it in terms of a member function on the second argument. 当然,您可以根据第二个参数上的成员函数来实现它。

Yes: 是:

class Rational {
  // ...
  friend Rational operator*(float lhs, Rational rhs) { rhs *= lhs; return rhs; }
};

Note: this is of course an abuse of the friend keyword. 注意:这当然是对friend关键字的滥用。 It should be a free function. 应该是一个免费功能。

Answer is no you cannot, but since float value is on left side you may expect that type of result from "0.5 * a" will be double. 答案是不可以,但是由于float值在左侧,因此您可能希望“ 0.5 * a”的结果类型会翻倍。 In that case you may consider doing something about conversion operator. 在这种情况下,您可以考虑对转换运算符做一些事情。 Please note that "pow(a, b)" is added only to illustrate the idea. 请注意,添加“ pow(a,b)”只是为了说明这一想法。

  1 #include <stdio.h>
  2 #include <math.h>
  3 
  4 class Complicated
  5 {
  6 public:
  7     Complicated(int a, int b) : m_a(a), m_b(b)
  8     {
  9     }   
 10      
 11     Complicated(double a) : m_a(a)
 12     {
 13     }
 14     
 15     template <typename T> operator T()
 16     {
 17         return (T)(pow(10, m_b) * m_a);
 18     }   
 19     
 20     void Print()
 21     {
 22         printf("(%f, %f)\n", m_a, m_b);
 23     }   
 24     
 25 private:
 26     double m_a;
 27     double m_b;
     28 };  
 29
 30 
 31 int main(int argc, char* argv[])
 32 {
 33     Complicated pr(1, 2);
 34     Complicated c = 5.1 * (double) pr;
 35     c.Print();
 36 }
 37 

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

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