我感觉这与我的派生运算符不使用基类的参数类型有关。
正是如此。基类必须采用 const引用(以便它可以具有动态类型Derived
,然后将覆盖声明为:
bool operator ==(const Base& rhs) const {
const auto pRhs = dynamic_cast<const Derived*>(&rhs);
if (pRhs == nullptr)
{
return false; // Not a derived. Cannot be equal.
}
// Derived/Derived implementation goes here
}
但请注意:像这样的虚拟比较运算符很容易出错。你需要一个很好的激励例子来做到这一点。特别是,如果你写:
Derived d;
Base b;
if (d == b) // All is well - derived override called, and returns false.
if (b == d) // Uh-oh! This will call the *base* version. Is that what you want?
还:
Derived d;
DerivedDerived dd;
if (d == dd) // Did you want to use the DerivedDerived comparison?