如何在 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;
}

尝试二 我觉得这会更好,但我有两个错误

  1. dynamic_cast 不能丢弃 const 或其他类型限定符
  2. 指针 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 (将#修改为@)