Overloading operator order [duplicate]

2019-05-19 17:54发布

问题:

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

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?

回答1:

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.



回答2:

As a free function:

Point operator+(float other, const Point &pt) {
    return pt+other;
}


回答3:

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


回答4:

Outside of the class:

inline Point operator+(const float& other, const Point& pnt) { return Point(...); };