如何重载一元减运算符在C ++? [英] How to overload unary minus operator in C++?
本文介绍了如何重载一元减运算符在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在实现向量类,我需要得到一个相反的向量。是否可以使用操作符重载定义这个方法?
I'm implementing vector class and I need to get an opposite of some vector. Is it possible to define this method using operator overloading?
这里是我的意思:
Vector2f vector1 = -vector2;
以下是我希望此运算符完成的操作:
Here's what I want this operator to accomplish:
Vector2f& oppositeVector(const Vector2f &_vector)
{
x = -_vector.getX();
y = -_vector.getY();
return *this;
}
感谢。
推荐答案
是,但不提供参数:
class Vector {
...
Vector operator-() {
// your code here
}
};
注意,你不应该返回* this。一元 - 运算符需要创建一个全新的Vector值,而不是改变它应用于的东西,所以你的代码可能看起来像这样:
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;
}
};
这篇关于如何重载一元减运算符在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文