简体   繁体   中英

How to overload unary minus operator in 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?

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.

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

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.

Was just looking for the answer for this, while designing high precision arithmetic library in C++ (based on GMP). Contrary to what's been said, that unary "-" has to return new value, this code works for me:

bigdecimal& bigdecimal::operator - () {
    mpf_neg(this->x, this->x);//set left mpf_t var to -right
    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM