can we use operator overloading to change behaviour of Minus [duplicate]
can we use operator overloading to change behaviour of Minus [duplicate]
This question already has an answer here:
is it possible using operator overloading to change the behavior of minus operator on integers in C++?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
No!
If you want to overload an operator, the argument of your operator must contain at least one user-defined type.
For example, in this case, you can overload minus for an integer and a class.
int main(void) class Integer int _data = 0; public: Integer& operator+(int term/*non user defined param*/) _data += term; return *this; ; Integer someInt; someInt + 5/*non user defined argument*/;
@George Yes, you're right. I didn't want to go to the detail of operator overloading. As you said, they are two ways to overload an operator. The first way that you mentioned is to introduce it as a thing that operates on an object of the class. Here it means for a given object of a class this is like obj.operator-(int) but here again, we're modifying operator on the class, not in the general. The second way as I mentioned in my answer is to define the operator independent of the object. That it is some sort of a function that it takes one integer and another object of the class.
– Amir Tavakkoli
Sep 1 at 9:43
No, you can't overload your own operators for intrinsic data types.
You can however create your own class / struct to represent an integer type and overload the operator-() for that one:
class
struct
operator-()
struct MyInt
int i;
int operator-() return +i;
;
Probably just a terminology mixup but "If you want to overload an operator, the argument of your operator must contain at least one user-defined type" is not strictly true.
int main(void) class Integer int _data = 0; public: Integer& operator+(int term/*non user defined param*/) _data += term; return *this; ; Integer someInt; someInt + 5/*non user defined argument*/;– George
Sep 1 at 9:14