| Thread overview | |||||
|---|---|---|---|---|---|
|
December 05, 2012 opEquals for same type | ||||
|---|---|---|---|---|
| ||||
interface I
{
// ...
bool opEquals(I i);
}
class C : I
{
// ...
bool opEquals(I i)
{
return true;
}
}
void main()
{
I i1 = new C;
I i2 = new C;
assert(i1 == i2); // Assertion failure
assert(i1 != i2); // Passes, although it's the opposite of what I want...
}
What's missing?
| ||||
December 05, 2012 Re: opEquals for same type | ||||
|---|---|---|---|---|
| ||||
Posted in reply to deed | On 12/04/2012 04:12 PM, deed wrote: > interface I > { > // ... > bool opEquals(I i); > } > > class C : I > { > // ... > bool opEquals(I i) > { > return true; > } > } > > void main() > { > I i1 = new C; > I i2 = new C; > assert(i1 == i2); // Assertion failure > assert(i1 != i2); // Passes, although it's the opposite of what I want... > } > > What's missing? opEquals is a special function of Object but interface's do not inherit from Object. Just override it on the class: interface I { // ... // bool opEquals(I i); } class C : I { int i; // ... override bool opEquals(Object o) const { auto rhs = cast(const C)o; return (rhs && (i == rhs.i)); } } void main() { I i1 = new C; I i2 = new C; assert(i1 == i2); } What I know about this topic is in the following chapter: http://ddili.org/ders/d.en/object.html Ali -- D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html | |||
December 05, 2012 Re: opEquals for same type | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli |
> What I know about this topic is in the following chapter:
>
> http://ddili.org/ders/d.en/object.html
>
> Ali
Thanks, Ali. That clarifies why it worked with opCmp and not with opEquals.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply