How do you overload opEquals?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Nov 19 13:10:55 PST 2013


On Tuesday, 19 November 2013 at 20:59:31 UTC, Dale Matthews wrote:
> I'm brand new to D and I'm taking on a project. In the midst, 
> I've overloaded a whole load of operators for my Vec3 class. 
> Most seem to be working (I haven't tested them all yet) but 
> opEquals is refusing to be called. I've followed the guidelines 
> here: http://dlang.org/operatoroverloading.html#equals
>
> class Vec3
> {
> public:
> 	float x, y, z;
> 	this(float xVal, float yVal, float zVal) { x = xVal, y = yVal, 
> z = zVal; }
> 	bool opEquals()(auto ref const Vec3 v) const
> 	{
> 		debug writeln("bool opEquals(Vec3) called");
> 		return x == v.x && y == v.y && z == v.z;
> 	}
> };
> unittest
> {
> 	Vec3 v = new Vec3(5, 10, 15);
> 	Vec3 v2 = new Vec3(5, 10, 15);
> 	//if(v.opEquals(v2))                      //this works great!
> 	if(v == v2)                                   //idk where this 
> goes off to but it returns false
> 		writeln("FINALLY");
> 	else
> 		writeln("try again?");
> }
>
> I've tried many variations of auto ref and const (although I'm 
> not sure how the function is different for each variation), and 
> it still doesn't get called. I feel like I'm missing something 
> simple.


     override bool opEquals (Object o) const {
         if ( auto v = cast( typeof( this ) ) o )
             return x == v.x && y == v.y && z == v.z;
         return false;
     }


You need:
1) 'override' in order to override the base class implementation.
2) 'Object' typed parameter, then cast.


More information about the Digitalmars-d-learn mailing list