opEquals footprint
xs0
xs0 at xs0.com
Wed Mar 22 07:39:40 PST 2006
Erik Rasmussen wrote:
> xs0 wrote:
>> int opEquals(Object)
>>
>> so it overrides the default implementation found in, you guessed it,
>> Object :) Same goes for opCmp, I think..
>>
>>
>> xs0
>
> So what's the best way to actually check the type in the opEquals/opCmp
> method? Something like...
>
> class A
> {
> int opEquals(Object o)
> {
> // check for null
> if(o is null)
> return false;
> // check type
> if(typeid(typeof(o)) != typeid(A))
> return false;
> // cast
> A that = cast(A) o;
> // actually check fields
> return this.a == that.a && this.b == that.b && ...;
> }
> }
>
> Or is there a better way? asserts?
>
> How do you hard-core D programmers usually do it?
>
> Cheers,
> Erik
Something like this should be ok:
// optional
if (this is o)
return true;
if (A that = cast(A)o) { // checks for null, too
return this.a==that.a && ...
} else {
return false;
}
OTOH, if you want to return false for subclasses, your version seems
fine to me.
xs0
More information about the Digitalmars-d-learn
mailing list