如何判断两个多态对象是否相等
How to see if two polymorphic objects are equal?
如何判断两个多态对象是否相等?例如
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
}
我会使用"好奇循环模板"模式,但是在基类和派生类之间有一个辅助类。
首先,在基类A
中添加纯虚拟的operator==
。
template<typename Base, typename Derived>
struct PolymorphicComparable : public Base {
...
};
在这个类中,您实现operator==
(如果Base==A
稍后,这将是一个覆盖):
bool operator==(const Base &other) const {
// first check if the dynamic types match
if (typeid(other) != typeid(Derived))
return false;
// cast to the concrete types; thanks to the check above this is safe
const Derived & a = static_cast<const Derived&>(*this);
const Derived & b = static_cast<const Derived&>(other);
// redirect to Derived::operator==(Derived)
return a == b;
}
现在,你的A
的子类不直接子类化A
,而是上面的类(这是"奇怪的循环模板"),每个实现自己的operator==
,不需要额外的代码:
struct A1 : public PolymorphicComparable<A,A1>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
int i;
bool operator==(const A1 &other) const {
return i == other.i;
}
};
注意:帮助类模板只需要一次,不仅对每个基类一次,而且在整个代码库中一次,即使你有多个基类,你想基于多态类型进行比较。
现场演示
-
为
operator==
函数在A
中创建虚成员函数。使用operator==
实现operator!=
.struct A { virtual bool operator==(A const& other) const = 0; bool operator!=(A const& other) const { return !(*this == other); } };
-
在具体类中实现
operator==
函数,并添加必要的检查struct A1 : public A { int i; virtual bool operator==(A const& other) const { // Do dynamic cast to make sure that other is of type A1. A1 const* otherPtr = dynamic_cast<A1 const*>(&other); if ( otherPtr == NULL ) { return false; } else { return i == otherPtr->i; } } };
如果A
在比较两个对象时需要考虑数据…
struct A
{
virtual bool operator==(A const& other) const
{
return (j == other.j);
}
bool operator!=(A const& other) const
{
return !(*this == other);
}
int j;
};
struct A1 : public A
{
int i;
virtual bool operator==(A const& other) const
{
if ( !(A::operator==(other)) )
{
return false;
}
// Do dynamic cast to make sure that other is of type A1.
A1 const* otherPtr = dynamic_cast<A1 const*>(&other);
if ( otherPtr == NULL )
{
return false;
}
else
{
return i == otherPtr->i;
}
}
};
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 通过switch和static_cast访问多态对象的运行时类型
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- C++ 在堆栈中包含多态属性的类对象存储
- 转身多态对象
- 多态对象的数组
- C++ 多态模板类,模板类型对象的实例化
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- C++多态性:有没有办法找到对象成员函数的地址?
- C++ 被此代码与多态性、指针和对象切片混淆
- 了解C++中多态对象的序列化
- 具有多态性的对象声明中的逗号
- 如何复制多态对象
- 使用多态性时在子对象之间进行转换?
- 多态性的面向对象方法
- 分配分配器为多态对象分配内存
- 将多态对象存储在unordered_set中
- 如何使用多态性将相同的操作应用于具有相同基类的不同对象的unordered_sets
- 使用数组对对象的编译时多态性是否可行?
- C++对象多态性问题