当我的对象位于 C++ 的右侧时,如何重载运算符 *?
我想在我的类中实现“operator *”重载,这样我就能够执行以下操作:
Rational a(1, 2), b;
b = 0.5 * a; // b = 1/4
注意 b 在右侧,有没有办法在内部做这样的事情”理性”类?
I want to implement "operator * " overloading INSIDE my class, so I would be able to do the following:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是:
注意:这当然是对
friend
关键字的滥用。它应该是一个免费函数。Yes:
Note: this is of course an abuse of the
friend
keyword. It should be a free function.不可以。您必须将
operator*
定义为自由函数。当然,您可以根据第二个参数的成员函数来实现它。No. You must define
operator*
as a free function. Of course, you could implement it in terms of a member function on the second argument.答案是否定的,你不能,但由于浮点值位于左侧,你可能期望“0.5 * a”的结果类型将是双精度的。在这种情况下,您可以考虑对转换运算符进行一些处理。请注意,添加“pow(a, b)”只是为了说明这个想法。
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. In that case you may consider doing something about conversion operator. Please note that "pow(a, b)" is added only to illustrate the idea.