Why does this opCmp function not work

Stefan Koch uplink.coder at googlemail.com
Wed Sep 23 10:38:42 UTC 2020


On Wednesday, 23 September 2020 at 10:37:09 UTC, Ruby The 
Roobster wrote:
> So, here we have an opCmp function for a class named shape. It 
> compares the .volume of each shape:
>
>  int opCmp(shape rhs)
> {
>     int exp;
>     if(this.volume == rhs.volume)
>         exp =  0;
>     else if(this.volume > rhs.volume)
>         exp =  1;
>     else if(this.volume < rhs.volume)
>         exp = -1;
>     return exp;
>
> }
>
> here is how I would use it:
> shape test = new shape(pos);/*Ignore the constructor argument 
> it's not relevant here*/
> shape test1 = new shape(pos); //same variable
> writeln(test == test1);
> writeln(test.opCmp(test1) == 0);
>
> Both .volume are the same, but the output says this:
>
> false
> true
>
> note that the documentation for comparing classes with an opCmp 
> function defined is said to be this: x.opCmp(y) op 0
>
> can anybody explain this to me?

Equality is defined by opEquals.
Which for classes defaults to pointer identity comparison.


More information about the Digitalmars-d mailing list