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.





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


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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?