C++ 在运算符重载中使用带有常量引用的友元函数
下面的代码无法编译。然而,当我从friend函数的Point&中删除“const”时,这段代码将被编译。谁能解释一下原因吗C++ 在运算符重载中使用带有常量引用的友元函数,c++,operator-overloading,friend,const-reference,C++,Operator Overloading,Friend,Const Reference,下面的代码无法编译。然而,当我从friend函数的Point&中删除“const”时,这段代码将被编译。谁能解释一下原因吗 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;} pr
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(){}
运算符+未标记为常量,但尝试通过常量引用调用。
常量指针和引用只允许调用标记为常量的成员函数(因为编译器明确知道这些函数不会修改内部状态)。运算符+未标记为常量,但尝试通过常量引用调用。 常量指针和引用只允许调用标记为常量的成员函数(因为编译器明确知道这些函数不会修改内部状态)