Operators overloading in D2 again
Robert Clipsham
robert at octarineparrot.com
Sun May 2 06:12:20 PDT 2010
On 02/05/10 07:14, Dan wrote:
> Hi everyone,
>
> is there anyway to do this with operators overloading? :
The following code does it:
----
class Tester
{
double x = 0.0;
T opBinary(string op:"+", T)(T value) if(is(T : double))
{
return x+value;
}
T opBinary(string op:"+", T)(T other) if(is(T : Tester))
{
Tester ret = new Tester;
ret.x = this.x + other.x;
return ret;
}
}
int main(char[][] args)
{
Tester t1 = new Tester;
Tester t2 = new Tester;
t1.x = 1.0;
t2.x = 2.0;
Tester t3 = new Tester;
t3 = t1+t2;
assert (t3.x == 3.0);
return 0;
}
----
Some variations from the original code:
- Fixed the assert ==, not =
- Made sure all testers are initialised... Don't forget to instantiate
classes before you use them, otherwise you'll end up with segmentation
faults
- Fixed a semantic error in the latter of the binary functions - an
empty Tester is at 0, if you want to add them you need to make sure you
do that, not just add other
I'd also advise you replace Tester with a struct if you won't be needing
inheritance, this way you save some memory overhead, and don't have to
remember to use = new Tester; Hope this helps :)
More information about the Digitalmars-d-learn
mailing list