Operator Overloading in struct

后端 未结 4 1607
無奈伤痛
無奈伤痛 2021-02-07 11:39

Suppose I define this structure:

struct Point {
   double x, y;
};

How can I overload the + operator so that, declared,

         


        
4条回答
  •  情深已故
    2021-02-07 12:19

    Here is how I would do it.

    struct Point {
       double x, y;
       struct Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
       struct Point& operator+=(const double& k) { x += k; y += k; return *this; }
    };
    
    Point operator+(Point lhs, const Point& rhs) { return lhs += rhs; }
    Point operator+(Point lhs, const double k) { return lhs += k; }
    Point operator+(const double k, Point rhs) { return rhs += k; }
    

提交回复
热议问题