【发布时间】:2014-06-16 17:46:09
【问题描述】:
如何判断两个多态对象是否相等?例如
struct A {};
struct A1 : public A
{
int i;
bool operator==(A1 const& other) const { return i == other.i; }
};
struct A2 : public A
{
float f;
bool operator==(A2 const& other) const { return f == other.f; }
};
bool isEqual(A const& x, A const& y)
{
if (typeid(x) != typeid(y))
return false;
... // Then how to compare when they have same type. Any way to cast them
// to their dynamic types by typeid or others
}
【问题讨论】:
-
查看访问者模式。你需要实现类似的东西或者使用
dynamic_cast和virtual bool equals(base const & other) const。 -
您是否尝试过编译问题中已经存在的代码?
-
你为什么要这样做?由于 A1+A2 没有 ==,所以它不会编译,所以你可以安全地比较 x 和 y,不是吗?这个问题对我来说不是很清楚。
-
@quantdev 如果使用多态,它们的静态类型将是 A 和 A。 IE。你有一些
vector<A*>来存储 A1 和 A2,现在的问题是:如何将两个这样的对象(不是它们的指针)与覆盖的比较进行比较? -
我不确定您在寻找什么。如果它们具有相同的类型,您是否要检查二进制相等对象(即所有内容位到位相等)?或者您想使用成员数据的子集进行比较(如果有一些与比较无关的 tmp 数据)?还是您在寻找多态相等?
标签: c++ polymorphism