比较对象和继承
在我的程序中,我有以下类层次结构:
class Base // Base is an abstract class
{
};
class A : public Base
{
};
class B : public Base
{
};
我想执行以下操作:
foo(const Base& one, const Base& two)
{
if (one == two)
{
// Do something
} else
{
// Do something else
}
}
我在这里遇到有关 operator==()
的问题。当然,比较A
实例和B
实例是没有意义的,但比较Base
的两个实例应该是可能的。 (你不能比较狗和猫,但你可以比较两种动物)
我想要以下结果:
A == B
=>假
A == A
=>true
或false
,取决于两者的有效值实例
B == B
=>true
或false
,取决于两者的有效值实例
我的问题是:这是一个好的设计/想法吗?这可能吗?我应该编写/重载哪些函数?
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
=>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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重载基类的运算符:子类引用将转换为基类引用。
在没有更多背景的情况下看不出设计有任何问题。
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...