[英]Casting a const base reference to derived
我有一个问题,但是我不知道我是否解决了正确的问题,或者是否有更多正确的方法。
现在,我有两个类(一个继承自另一个):
class Data_Base
{
...
}
class Data_Error : public Data_Base
{
...
}
现在,在相等运算符的重载中,我必须再次将对基础对象的const引用强制转换为派生对象,以测试其成员。 目前,我正在这样做:
bool Data_Error::operator==(const Data_Base &other) const
{
if (Data_Base::operator !=(other))
return false;
const Data_Error &other_cast = (const Data_Error &)other;
... More tests on other_cast ...
}
现在,在Data_Error
, other
变量Data_Error
是Data_Base
以外的other
变量,因为Data_Base
==
运算符(以及!=
运算符,因为它是==
的取反)也可以检查的类型。派生对象,因此只有类型正确时,它才到达该行。
现在,这有什么问题吗? 有没有“更正确”的解决方案?
我正在使用Qt(5.7),所以有“更多的QTish”解决方案吗?
应避免使用C型转换。 您可以在这里找到原因。 您应该改为使用静态转换:
const Data_Error &other_cast = static_cast<const Data_Error &>(other);
或动态转换以在运行时检查其他有效类型为Data_Error:
const Data_Error &other_cast = dynamic_cast<const Data_Error &>(other);
正确的方法是对指针使用dynamic_cast
,因为如果对象不是正确的派生类型,它只会返回null。 您的示例将变为:
bool Data_Error::operator==(const Data_Base &other) const
{
if (Data_Base::operator !=(other))
return false;
const Data_Error *other_cast = dynamic_cast<const Data_Error *>(&other);
if (other_cast == nullptr) { // not the correct type
return false;
}
... More tests on *other_cast ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.