哪种方式可以更有效地重载运算符,为什么?

Which way to overload the operator more efficiently and why?

哪种方式更有效? this->X 或只是 X 有什么区别吗?我认为它 'void' 版本 bcs 编译器不需要调用构造函数或 smth,只需添加。

void operator+=(vect right)
{
    this->x += right.x;
    this->y += right.y;
}

void operator+=(vect right)
{
    x += right.x;
    y += right.y;
}

vect& operator+=(vect right)
{
    x += right.x;
    y += right.y;
    return *this;
}

版本 1 和版本 2 做的事情完全一样,没有区别。版本 3 允许您编写

vecA += vecB += vecC += vecD;

在性能上没有区别,运算符returns是对自身的引用,而不是新对象。

如果您关心效率,请首先不要将复杂类型作为值参数。

vect& operator+=(vect const& right)
{
    x += right.x;
    y += right.y;
    return *this;
}

this->x 和普通的 x 意思相同。它们根本不影响运行时。最后,return vect& 因为 it's idiomatic.