views:

733

answers:

4

Hello,

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.

A: 
Vector2f operator-(const Vector2f &_vector)
{
   Vector2f result;
   result.setX(-_vector.getX());
   result.setY(-_vector.getY());

   return result;
}

And you could also want overload other related operators as well:

class Vector2f
{
public:
   // ...
   Vector2f& operator-=(const Vector2f& other);
};

// binary minus
Vector2f operator-(const Vector2f& lhs, const Vector2f& rhs)
{
    Vector2f result = lhs;
    return result -= rhs;
}

And don't forget to put these operators in same namespace with Vector2f.

Alexander Poluektov
how can this work if there is no left-hand side expression?
Alex Brown
That's wrong. Why is `_vector` needed if you're at class scope? Why are you returning a copy of *this*, but modify the object itself?
Alexander Gessler
@Alex: The "unary minus" operator?
Cwan
@Alexander Gessler: you are right, shame on me. Edited.
Alexander Poluektov
+7  A: 

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.

Alexander Gessler
+1 for catching that you need to return a new Vector2f instance, not a reference to the current object.
MikeSep
+18  A: 

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;
   }
};
anon
+1 : the only right solution -_-
Kornel Kisielewicz
it's wrong: it should be v.x = -x; v.y = -y;
sergiom
A: 

minus operator (-) with special refrence to to the complex class.the process of defining the the minus operator is quite similar to that of the plus operator.it is binary operator,having two arguments.both the arguments will be complex numbers.when we are subtract two complex number,it always return complex number."Subtract the real part from real part and subtract the imaginary part from the imaginary one".

       Complex operator-(Complex c)
Wajahat Bashir