Operators overloading in D2 again
Ali Çehreli
acehreli at yahoo.com
Sat May 1 23:30:56 PDT 2010
Dan wrote:
> Hi everyone,
>
> is there anyway to do this with operators overloading? :
>
>
> class Tester
> {
> double x = 0.0;
>
> double opBinary(string op:"+")(double value)
> {
> return x+value;
> }
>
> Tester opBinary(string op:"+")(Tester other)
> {
> Tester ret;
> ret.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;
> t3 = t1+t2;
> assert (t3.x = 3.0);
>
> return 0;
> }
>
>
> Thanks,
> Dan
Functions can not be overloaded by return type alone; so I took the one
that returned double out.
We are dealing with a Tester class, and it makes sense to me to stay in
this type. When necessary, we can provide a conversion function that
returns a double value.
I've corrected a couple of errors, introduced a constructor, and came up
with this:
class Tester
{
double x = 0.0;
this(double x)
{
this.x = x;
}
Tester opBinary(string op:"+")(const Tester other) const
{
return new Tester(x + other.x);
}
}
int main(char[][] args)
{
Tester t1 = new Tester(1.0);
Tester t2 = new Tester(2.0);
Tester t3 = t1 + t2;
assert (t3.x == 3.0);
return 0;
}
Ali
More information about the Digitalmars-d-learn
mailing list