Operator Overloading in struct

后端 未结 4 1608
無奈伤痛
無奈伤痛 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:03

    Just do it:

    Point operator+( Point const& lhs, Point const& rhs );
    Point operator+( Point const& lhs, double rhs );
    Point operator+( double lhs, Point const& rhs );
    

    With regards to your last question, the compiler makes no assumptions concerning what your operator does. (Remember, the + operator on std::string is not commutative.) So you have to provide both overloads.

    Alternatively, you can provide an implicit conversion of double to Point (by having a converting constructor in Point). In that case, the first overload above will handle all three cases.

提交回复
热议问题