如何解决如何在 C++17 的抽象类中重载 operator==?
我需要为抽象类实现一个 operator==。层次结构如下所示:
hpp
class Abstract{
public:
virtual const std::string& exampleFunc() const = 0;
//
// ...
//
bool operator== (const Abstract& rhs) const; // Need help here
};
class SubOne final : public Abstract{
private:
const std::string infoOne;
public:
//
// ...
//
bool operator== (const SubOne& rhs) const;
};
class SubTwo final : public Abstract{
private:
int infoTwo;
public:
//
// ...
//
bool operator== (const SubTwo& rhs) const;
};
cpp
bool SubOne::operator== (const SubOne& rhs) const{
if ( this->infoOne == rhs.infoOne){
return true;
}
return false;
}
bool SubTwo::operator== (const SubTwo& rhs) const{
if ( this->infoTwo == rhs.infoTwo){
return true;
}
return false;
}
到目前为止,我已经进行了两次尝试,但都没有成功。
尝试一个 这个不会出错,但它并不是一直有效。
bool Abstract::operator== (const Abstract& rhs) const{
std::string left = typeid(*this).name();
std::string right = typeid(rhs).name();
if (left == right){
return true;
}
return false;
}
- dynamic_cast 不能丢弃 const 或其他类型限定符
- 指针 dynamic_cast 的操作数必须是指向完整类类型的指针
bool Abstract::operator== (const Abstract& rhs) const{
SubOne* left = dynamic_cast<SubOne*>(this);
SubOne* right = dynamic_cast<SubOne*>(rhs);
if (left){
if (right){
return true;
}
else{
return false;
}
}
else if (right){
return false;
}
return true;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。