On 07/08/2013 02:21 PM, Ugbar Ikenaki wrote:
I'm trying to implement rational numbers with fully functioning
comparison operators, but I can't seem to figure out why I'm getting
this error and any help would be appreciated:
Error: cannot cast from object.Object to Rat
The code I have is as follows:
int opCmp( Object o ) {
Rat other = cast(Rat) o; <--- this line throws the error
…
//stuff to return -1, 0, or 1 to opCmp with rational numbers
for <, >=, etc.
…
}
Thanks to anyone who can help!
Yeah, the signature of opCmp is different for structs so you don't need
to cast.
Once you have the subtraction defined, opCmp can be as simple as the
following:
/* Sort order operator: Returns a negative value if this
* fraction is before, a positive value if this fraction
* is after, and zero if both fractions have the same sort
* order. */
int opCmp(const ref Fraction rhs) const
{
immutable result = this - rhs;
/* Being a long, num cannot be converted to int
* automatically; it must be converted explicitly by
* 'to' (or cast). */
return to!int(result.num);
}
I have a couple of chapters that go over operator overloading.
Operator Overloading:
http://ddili.org/ders/d.en/operator_overloading.html
Object is specifically for classes:
http://ddili.org/ders/d.en/object.html
Ali