I may not be using the right word here and that could be why I can't find the answer on my own. I have a + & - operator in my class, but I want to add a negative operator... I basicly what to be able to do this:
myMethod(myClass, -myClass);
If you need code examples to help me out let me know, but I think this should be pretty strait forward... Or that it can't be done.
Now, if the user wants to make the operator “+” to add two class objects, the user has to redefine the meaning of “+” operator such that it adds two class objects. This is done by using the concept “Operator overloading”. So the main idea behind “Operator overloading” is to use c++ operators with class variables or class objects.
Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. C/C++ has many built-in operator types and they are classified as follows:
C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
In the C language, you have several ways to create a negative integer: You can assign a negative value to a variable, you can perform math that results in a negative value, or you can manipulate bits to convert a positive value to a negative one. That final operation isn’t as easy as it sounds.
Sure, the unary -
operator is overloadable:
public static MyClass operator -(MyClass myClass)
{
...
}
Be careful not to abuse these features as consumers may be unaware of the semantics of these operators - unlike methods (which can be well-named), it is often not immediately obvious what a custom operator on a type does. Hopefully, your class represents a vector of some sort or similar?
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