重载操作员订单 [英] Overloading operator order

查看:174
本文介绍了重载操作员订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

操作符在C ++中重载为int + obj

运算符重载 c ++ -faq

我有一个 object with this operator:

I have a Point object with this operator:

Point operator +(float other) const {
  return Point(x + other, y + other, z + other);
}

我可以这样执行添加:

point + 10

不要以相反的顺序执行:

But I can't perform it in reverse order:

10 + point

是否还有另一个运算符需要重载才能提供此功能?

Is there another operator I need to overload in order to provide this functionality?

推荐答案

您通常想要重载全局运算符:

You normally want to overload the global operator:

Point operator+(Point const &a, float b);
Point operator+(float a, Point const &b);

而不是两个重载,您可能只想使用一个重载:

Instead of two overloads, you may want to use only one overload:

Point operator+(Point const &a, Point const &b);

,然后使用ctor从浮点创建点:

and then have a ctor to create a Point from a float:

class Point { 
    public:
        Point(float);
};

在这种情况下,向Point添加一个float将使用ctor将float转换为Point ,然后使用重载的操作符+将这两个点添加在一起。

In this case, adding a float to a Point will use the ctor to convert the float to a Point, then use your overloaded operator+ to add those two Points together.

这篇关于重载操作员订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆