Why does this opCmp function not work
Steven Schveighoffer
schveiguy at gmail.com
Wed Sep 23 11:58:15 UTC 2020
On 9/23/20 7:28 AM, Simen Kjærås wrote:
> On Wednesday, 23 September 2020 at 11:19:15 UTC, Ruby The Roobster wrote:
>> bool opEquals(shape rhs)
>> {
>> return(rhs.volume == this.volume);
>> }
>
> This is a wrong implementation of opEquals for a class. The
> documentation mentions
> (https://dlang.org/spec/operatoroverloading.html#equals):
>
>> 4. If overridding Object.opEquals() for classes, the class member
>> function signature should look like:
>>
>> class C
>> {
>> override bool opEquals(Object o) { ... }
>> }
>
> A correct implementation would be:
>
> override bool opEquals(Object o) {
> if (!cast(Shape)o) return false;
> return (cast(Shape)o).volume == this.volume;
> }
Or, more D way:
if(auto other = cast(Shape)o) return other.volume == this.volume;
return false;
-Steve
More information about the Digitalmars-d
mailing list