[help]operator overloading with opEquals in a class

Jonathan M Davis jmdavisProg at gmx.com
Wed Nov 3 10:58:05 PDT 2010


On Wednesday, November 03, 2010 05:07:25 zhang wrote:
> This code belown can be compiled with DMD 2.050. However, it throws an
> error message: core.exception.HiddenFuncError: Hidden method called for
> main.AClass
> 
> I'm not sure about whether it is a bug. Thanks for any help.
> 
> 
> 
> import std.stdio;
> 
> class AClass
> {
>     int data;
> 
> // It's wrong
>     bool opEquals(AClass a)
>     {
>         writefln("running here.");
>         return data == a.data;
>     }
> 
> // It works
> //    bool opEquals(Object a)
> //    {
> //        writefln("running here.");
> //        return data == (cast(AClass)a).data;
> //    }
> 
> }
> 
> 
> int main(string[] args)
> {
> 
>     AClass class1 = new AClass();
>     AClass class2 = new AClass();
> 
>     if(class1 == class2)
>         writefln("==");
>     else
>         writefln("!=");
> 
>     return 0;
> }
> 
> ----------
> Zhang <bitworld at qq.com>
> 
> s


Take a look at the section on overloading == and != here: 
http://www.digitalmars.com/d/2.0/operatoroverloading.html

You should only be defining the version of opEquals() that takes an Object.

- Jonathan M Davis


More information about the Digitalmars-d mailing list