Overload unary minus operator in C++?This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands. The increment (++) and decrement (--) operators. The unary minus (-) operator.
You can overload a prefix or postfix unary operator by declaring a nonstatic member function taking no arguments, or by declaring a nonmember function taking one argument. If @ represents a unary operator, @x and x@ can both be interpreted as either x.
Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.
The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With