Re: operator overloading for primative types
On 2007-09-28 00:07, Me wrote:
On Thu, 27 Sep 2007 15:51:26 +1200, Noone wrote:
PengYu.UT@gmail.com wrote:
Hi,
It seems that C++ does not allow overloading operators for primative
types, e.g. int, double. I'm wondering whether it is ture or there is
some walk-around?
Luckily you can't, doing so would produce code that doesn't behave as
others would expect it to, a nightmare to maintain.
If you want a type with specialised behavior, wrap it in a class with
the appropriate operators.
Yes. I believe in the Macrosloth world they call that boxing:
encapsulating a primitive type in an object so that it can be manipulated
by other classes as a generic (Object), with whatever behavior the
programmer wants to implement. I pass no judgement on whether this is a
good thing or a bad thing. :^)
[Off topic]
The goal of boxing is to be able to place a value type on the managed
heap, so that it can be accessed by methods (and other things) that only
accept reference types. The equivalent in C++ would be something like this:
int a;
int* boxedA = new int(a);
One important thing to notice is that the boxed object and the non-boxed
are two separate objects with no connection what so ever (except having
the same value).
Specifically you can not take an int, box it, and then apply some user
defined operators on it. To do that you would have to create a value
type with overloaded operators and then box that. Which would be the
same as creating a new type in C++ and overloading its operators.
[/Off topic]
--
Erik Wikstr??m