重写运算符以在C中使用派生类
作者:互联网
我试图覆盖子类中的虚拟比较运算符,但我得到一个编译器错误,说派生类没有实现基类的虚拟运算符.
我感觉这与我的派生运算符不使用基类’参数类型这一事实有关.
简化版如下:
struct Base {
virtual bool operator ==(const Base) const;
};
struct Derived : Base {
bool operator ==(const Derived) const {
// implementation goes here
}
};
有没有办法让我这样做,或者我是否必须在Derived实现中进行类型检查以查看它是否是正确的类型?
解决方法:
I have a feeling it’s to do with the fact that my derived operator
doesn’t use the base class’ argument type.
正是如此.基类必须采用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?
标签:method-overriding,subtyping,c,operator-overloading,inheritance 来源: https://codeday.me/bug/20190828/1755398.html