C++ 实现具有多级继承的对象相等性

标签 c++

我需要为具有多级继承的多个对象实现一个 isEqual 方法。出于这个原因,我决定不创建接口(interface),因为该方法不是纯虚拟的,而只是一个我可以稍后用作标记的类。

这些类实现了一个方法 isEqual。因为我需要定义默认行为,所以这些方法不是纯虚拟的。

class A_Interface {
    virtual isEqual(shared_ptr<A_Interface> obj);
    ...
    virtual otherMethod1();
}


class B_Interface : public virtual A_Interface {
    virtual isEqual(shared_ptr<B_Interface> obj);
    ...
    virtual otherMethod2();
}


class C_Interface : public virtual B_Interface {
    virtual isEqual(shared_ptr<C_Interface> obj);
    ...
    virtual otherMethod3();
}

每个类都实现了它自己的上面提到的“类接口(interface)”标记类,并像这样从父类继承:

class A : public virtual A_interface;
{
    isEqual(shared_ptr<A_Interface> obj){
    ...
    }
};



class B : public virtual A, 
          public virtual B_interface 
                {
    using A::isEqual;
    isEqual(shared_ptr<B_Interface> obj){
    ...
    }
};


class C : public virtual B,
          public virtual C_interface 
  {
    using B::isEqual;
    isEqual(shared_ptr<C_Interface> obj){
    ...

    bool parentIsEquals = B::isEqual(obj);

    ...
    }
};

为了避免在 B 类中隐藏名称,我明确声明了

using A::isEqual;

语句解决了问题,但现在在 C 类中,当我想引用方法“isEqual”父类 B 并像那样明确指定它时

bool parentIsEquals = B::isEqual(obj);

我得到了错误

"B::isEqual' is ambiguous"

我也理解,因为我有两个签名,即

using A::isEqual;
isEqual(shared_ptr<B_Interface> obj);

我不知道如何解决这个问题,因为本例中的参数“obj”确实匹配购买的签名。 我想了解是否有更好的模式/提议来实现这个问题。

最佳答案

保持简单。

具有以下类层次结构:

struct A     { int value1; };
struct B : A { int value2; };
struct C : B { int value3; };

您可以为 ABC 定义相等运算符

bool operator==(A const& lhs, A const& rhs)
{
    return lhs.value1 == rhs->value1;
}
bool operator==(B const& lhs, B const& rhs)
{
    return lhs.value2 == rhs->value2
           && static_cast<A const&>(lhs) == static_cast<A const&>(rhs);
}
bool operator==(C const& lhs, C const& rhs)
{
    return lhs.value3 == rhs->value3
           && static_cast<B const&>(lhs) == static_cast<B const&>(rhs);
}

加上一点糖:

template<class Wrapper>
bool operator==(A const& lhs, Wrapper const& rhs)
{ return lhs == *rhs; }
template<class Wrapper>
bool operator==(Wrapper const& rhs, A const& lhs)
{ return rhs == lhs; }
// and so on...

所有这些简单的函数都给了你很大的灵 active :

B b1{{1}, 2};
auto c2 = std::make_unique<C>(C{{{1}, 2}, 3});
bool const equals = b1 == c2; // true

关于C++ 实现具有多级继承的对象相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57723927/

相关文章:

c++ - 推荐的 GCC 发布构建标志

c++ - 代码错误 : (null): 5 duplicate symbols for architecture x86_64

c++ - BOOST_PP_REPEAT 中数据的多个参数

c++ - CPP - 在库中更改#define

c++ - 学习 C,我的编译器已经知道 bool (Visual Studio 2017)

c++ - Boost 多列索引的多索引复合键

C++ 基于输入参数的返回类型推导

C++:错误 LNK2019:函数 _main 中引用了未解析的外部符号

c++重载另一个类的赋值运算符

c++ - 为什么我没有正确解析?