How to overload a unary minus operator in C ++?

I am implementing a vector class, and I need to get the opposite of some vector. Is it possible to define this method using operator overloading?

Here is what I mean:

Vector2f vector1 = -vector2; 

Here I want this statement to execute:

 Vector2f& oppositeVector(const Vector2f &_vector) { x = -_vector.getX(); y = -_vector.getY(); return *this; } 

Thank.

+50
c ++ operator-overloading
Jan 28
source share
3 answers

Yes, but you do not provide it with a parameter:

 class Vector { ... Vector operator-() { // your code here } }; 

Please note that you must not return * this. The unary operator should create a completely new Vector value, and not change what it applies to, so your code might look something like this:

 class Vector { ... Vector operator-() const { Vector v; vx = -x; vy = -y; return v; } }; 
+91
Jan 28 '10 at 14:50
source share

it

 Vector2f operator-(const Vector2f& in) { return Vector2f(-in.x,-in.y); } 

May be inside the classroom or outside. My sample is in the namespace area.

+23
Jan 28 '10 at 14:50
source share

I just needed an answer for this, when developing a high-precision arithmetic library in C ++ (based on GMP). Contrary to what has been said, this unary "-" should return a 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; } 
0
Apr 05 '17 at 10:11
source share



All Articles