Comparing objects and inheritance
In my program I have the following class hierarchy:
class Base // Base is an abstract class
{
};
class A : public Base
{
};
class B : public Base
{
};
I would like to do the following:
foo(const Base& one, const Base& two)
{
if (one == two)
{
// Do something
} else
{
// Do something else
}
}
I have issues regarding the operator==()
here. Of course comparing an instance A
and an instance of B
makes no sense but comparing two instances of Base
should be possible. (You can't compare a Dog and a Cat however you can compare two Animals)
I would like the following results:
A == B
=>false
A == A
=>开发者_JS百科true
orfalse
, depending on the effective value of the two instances
B == B
=>true
orfalse
, depending on the effective value of the two instances
My question is: is this a good design/idea ? Is this even possible ? What functions should I write/overload ?
class Base // Base is an abstract class
{
virtual bool equals(const Base& b) = 0;
};
class A : public Base
{
virtual bool equals(const Base& base)
{
if (const A* a = dynamic_cast<const A*>(&base))
{
// Return true iff this and a are equal.
}
return false;
}
};
class B : public Base
{
virtual bool equals(const Base& base)
{
if (const B* b = dynamic_cast<const B*>(&base))
{
// Return true iff this and b are equal.
}
return false;
}
};
Overload the operator at the base: subclasses references will be casted to the base class reference.
Can't see any problem with the design - not without more context.
I can not craft a counterexample right now, but as far as I remember, the comparison operator (as something transitive, reflexive and symmetric) will always break (and be a source of malicious errors) when combined with inheritance. Possible it will not break you app, your use case, just half a year later when you subclass your subclass...
精彩评论