开发者

How to overload an operator in build-in class?

开发者 https://www.devze.com 2023-02-13 18:59 出处:网络
Somebody mentioned that it would make sense to overload + in e.g. Color struct. But how can I do it? I thought it needs to开发者_Python百科 be inside of the type.That\'s correct; there\'s no way to ad

Somebody mentioned that it would make sense to overload + in e.g. Color struct. But how can I do it? I thought it needs to开发者_Python百科 be inside of the type.


That's correct; there's no way to add operator overloading to an existing type (there are no extension operators).


I wouldn't pursue this - it would probably be cleaner to create an extension method Add(Color c1, Color c2)


Operators involve 2 operands, and you have the chance of placing the operator overload into eather of the 2 types involved.

In other words, you can write your own custom type, and add operators that makes it interact with Color, but if you want Color and int to interact with new operators, then sorry, no, you can´t do that.

0

精彩评论

暂无评论...
验证码 换一张
取 消