简体   繁体   中英

using friend function with const reference in operator overloading

The code below cannot be compiled. However, when I remove "const" from Point& of the friend function, this code turns to be compiled. Could anyone explain the reason why?

class Point
{
  public:
    Point(double x, double y);
    Point operator+(const double& add);
    friend Point operator+(const double& add, const Point& p){return p+add;}
  private:
    double px, py;
};

Point::Point(double x, double y): px(x), py(y){}
Point Point::operator+(const double& add){
  return(Point(px+add, py+add));
}
int main(){}

The operator+ is not marked as a const, yet is tried to be called through a const reference. Constant pointers and references are only allowed to call member functions that are marked constant (since the compiler definitely knows that those functions are ensured not to modify internal state).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM