Beginner problem: casting in opCmp override
Ugbar Ikenaki
iken8273 at uwi.com
Mon Jul 8 14:36:10 PDT 2013
Thanks for the quick response!
Here is the initialization code for my Rat struct. I created a
GCD function that I've tested to work fine:
import std.stdio, std.exception;
struct Rat {
private long n; //Numerator
private long d; //Denominator
public this( long numerator, long denominator ) {
enforce( denominator != 0, "Error. Denominator can not be 0.
(Rat.this)");
//Default 0-value Rat object
if( numerator == 0 || numerator == -0 ) {
n = 0;
d = 1;
} else {
//Assign appropriates signs (+ / -) to numerator
// -x/-y
if( numerator < 0 && denominator < 0 ) {
numerator = -numerator;
denominator = -denominator;
// x/-y
} else if( numerator > 0 && denominator < 0 ) {
numerator = -numerator;
denominator = -denominator;
}
//Find GCD of numerator and denominator
long gcd = gcd( numerator, denominator );
//Return reduced fraction of numerator and denominator
(invariant)
n = numerator / gcd;
d = denominator / gcd;
}
}
The following is the code to override the opCmp function:
int opCmp( Object o ) {
Rat other = cast(Rat) o;
long num1 = n;
long den1 = d;
long num2 = other.n;
long den2 = other.d;
//If denominators are not equal to each other...
if( den1 != den2 ) {
//Set denominators equal to each other (with corresponding
numerators)
num1 *= den2;
den1 *= den2;
if(den2 < den1) {
num2 *= (den1 / den2);
den2 *= (den1 / den2);
} else {
num2 *= (den2 / den1);
den2 *= (den2 / den1);
}
//Return opCmp int value (-1, 0, 1)
if( num1 - num2 < 0 ) {
return -1;
} else if( num1 - num2 == 0 ) {
return 0;
} else { //if( num1 - num2 > 0 )
return 1;
}
//If denominators are equal to each other...
} else {
//Less than
if( num1 - num2 < 0 ) {
return -1;
//Equal to
} else if( num1 - num2 == 0 ) {
return 0;
//Greater than
} else { //if( num1 - num2 > 0 )
return 1;
}
}
}
More information about the Digitalmars-d-learn
mailing list