你能解释一下返回值、引用值和 const 引用值之间的区别吗?
价值:
Vector2D operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
非常量参考:
Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
常量参考:
const Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
这有什么好处?我理解将 const 引用传递给函数背后的意义,因为您要确保不修改该引用指向函数内部的值。但是我对返回 const 引用的含义感到困惑。为什么返回引用优于返回值,为什么返回 const 引用优于返回非 const 引用?