How to overload unary minus operator in C++?

Solution 1:

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;
   }
};

Solution 2:

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.