如何为派生类创建有效的equals
方法?
struct Base {
virtual bool equals(const Base &other) const = 0;
};
通常的答案是使用
dynamic_cast
或typeid
检查派生类中的类型标识,如果类型匹配,则进行比较:struct Derived: Base {
virtual bool equals(const Base &other) const override {
if (typeid(*this)!=typeid(other)) return false;
return *this==static_cast<Derived &>(other);
}
};
有没有更有效的方法来进行类型检查?如果我们禁用了RTTI,该怎么办?
最佳答案
我认为核心问题是您不需要比较类型。这种需求总是显示出不良的设计,对继承的不正确使用或其他不良模式。
看看为什么您需要平等信息-接下来,您将通过调用继承并覆盖的类方法无法使用的平等信息呢?
关于c++ - 如何对派生类进行相等性测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46385588/