如何在 C++ 中重载一元减号运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2155275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to overload unary minus operator in C++?
提问by Ilya Suzdalnitski
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?
我正在实现向量类,我需要得到一些向量的对立面。是否可以使用运算符重载来定义此方法?
Here's what I mean:
这就是我的意思:
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;
}
Thanks.
谢谢。
回答by
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:
请注意,您不应返回 *this。一元 - 运算符需要创建一个全新的 Vector 值,而不是更改它所应用的对象,因此您的代码可能需要如下所示:
class Vector {
...
Vector operator-() const {
Vector v;
v.x = -x;
v.y = -y;
return v;
}
};
回答by Alexander Gessler
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.
可以在班内,也可以在班外。我的示例在命名空间范围内。