0

我有以下类层次结构:

class Base{
....
virtual bool equal(Base *);
}

class Derived1: public Base{
....
virtual bool equal(Base *);
}
class Derived2: public Derived1{
}
class Derived3: public Derived1{
}
class Derived4: public Base{
}

我应该如何编写 Base::equal(Base *) 函数来比较 Derived4 和类似的类?它们没有数据字段,所以只检查实际对象是否属于同一个派生类。

以及如何编写 Derived1::equal(Base) - Derived2 和 Derived3 相似,它们没有任何数据字段,应该通过 Derived1 中的数据字段进行比较并检查对象是否来自同一个派生类?

更新:我想要这个,因为我不想为每个派生类编写相同的函数,例如:

bool Derived::equal(Base *b){ 
  Derived *d = dynamic_cast<Derived*>(b); 
  return d; 
} 
4

2 回答 2

3

可用于多态类型间比较的通用技术称为“double dipatch”(请参阅​​ Double Dispatch)。它可以应用于您的特定问题,在这种情况下,您最终会得到一堆几乎为空的重载函数,只返回“false”或“true”。

当然,如果你只是想比较动态类型而不是其他,你可以通过运行时类型信息来完成(即使用'typeid')。

于 2009-10-11T08:39:18.970 回答
2

我认为您可以在这里使用typeid运算符。您可以执行以下操作:

typeid(*pointerBase) == typeid(*this);

但是你为什么要做这样的事情呢?看起来很可疑,我建议重新审视一下设计。

于 2009-10-11T07:33:26.357 回答