Overloading operator order [duplicate]

2019-05-19 17:26发布

Possible Duplicate:
Operator Overloading in C++ as int + obj
Operator overloading

I have a Point object with this operator:

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

I can perform addition like so:

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?

4条回答
Animai°情兽
2楼-- · 2019-05-19 17:55

Outside of the class:

inline Point operator+(const float& other, const Point& pnt) { return Point(...); };
查看更多
劳资没心,怎么记你
3楼-- · 2019-05-19 18:05

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

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

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

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.

查看更多
混吃等死
4楼-- · 2019-05-19 18:09

As a free function:

Point operator+(float other, const Point &pt) {
    return pt+other;
}
查看更多
对你真心纯属浪费
5楼-- · 2019-05-19 18:09

Given an existing Point& Point::operator+=(float other), add these two free functions:

Point operator+(Point pt, float other) {
  return pt += other;
}
Point operator+(float other, Point pt) {
  return pt += other;
}
查看更多
登录 后发表回答