如何在 C + + 中重载一元负运算符?

我正在实现向量类,我需要得到某个向量的对立面。有没有可能用运算符重载来定义这种方法?

我的意思是:

Vector2f vector1 = -vector2;

下面是我希望这个操作符完成的操作:

Vector2f& oppositeVector(const Vector2f &_vector)
{
x = -_vector.getX();
y = -_vector.getY();


return *this;
}

谢谢。

67855 次浏览

It's

Vector2f operator-(const Vector2f& in) {
return Vector2f(-in.x,-in.y);
}

Can be within the class, or outside. My sample is in namespace scope.

Yes, but you don't provide it with a parameter:

class Vector {
...
Vector operator-()  {
// your code here
}
};

Note that you should not return *this. The unary - operator needs to create a brand new Vector value, not change the thing it is applied to, so your code may want to look something like this:

class Vector {
...
Vector operator-() const {
Vector v;
v.x = -x;
v.y = -y;
return v;
}
};