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;
}
Mark Rotteveel
110k240 gold badges160 silver badges232 bronze badges
asked Jan 28, 2010 at 14:46
Ilya Suzdalnitski
53.6k51 gold badges137 silver badges172 bronze badges
2 Answers 2
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;
}
};
Sign up to request clarification or add additional context in comments.
2 Comments
AnT stands with Russia
@Kornel Kisielewicz: Calling it "the only right solution" is misleading. Unary
- can be overloaded by a standalone function as well, which would closely mirror the OP's implementation of oppositeVector.Chifti Saidi
Should return a const Vector.
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.
kennytm
526k110 gold badges1.1k silver badges1k bronze badges
answered Jan 28, 2010 at 14:50
Alexander Gessler
46.9k7 gold badges86 silver badges124 bronze badges
6 Comments
Mike Seplowitz
+1 for catching that you need to return a new Vector2f instance, not a reference to the current object.
Daniele Santi
This is the implementation of a binary operator-. Unary has no parameter as @anon said.
Alexander Gessler
Nope, it is an unary operator. It takes a
Vector2f as parameter since it is defined in namespace- rather than class scope. My response is correct.Alexander Gessler
See also 13.5.1 - 'A prefix unary operator shall be implemented by a non-static member function (9.3) with no parameters or a non-member function with one parameter'.
xis
@shunz it's an unary operator. note it is namespace scope not class scope.
|
lang-cpp
.getX()and.getY()on your simple Vector type