C++中派生类的等式测试

Imb*_*bue 12 c++ inheritance equality operators equals-operator

可能重复:
为类层次结构重载operator ==的正确方法是什么?

在C++中,派生类如何以有意义的方式覆盖基类相等性测试?

例如,假设我有一个基类A.类B和C派生自A.现在给出两个指向两个A对象的指针,我可以测试它们是否相等(包括任何子类数据)吗?

class A {
    public: int data;
};

class B : public A {
    public: float more_data; bool something_else;
};

class C : public A {
    public: double more_data;
};


    A* one = new B;
    A* two = new B;
    A* three = new C;

    //How can I test if one, two, or three are equal
    //including any derived class data?
Run Code Online (Sandbox Code Playgroud)

这样做有干净的方法吗?什么是我最好的选择?

谢谢!

小智 14

我记得读过公共 - 非虚拟/非公共 - 虚拟习语及其优点的简洁描述,但不是在哪里. 这个wikibook有一个很好的描述.

以下是将其应用于op ==的方法:

struct A {
  virtual ~A() {}

  int a;

  friend
  bool operator==(A const& lhs, A const& rhs) {
    return lhs.equal_to(rhs);
  }
  // http://en.wikipedia.org/wiki/Barton-Nackman_trick
  // used in a simplified form here

protected:
  virtual bool equal_to(A const& other) const {
    return a == other.a;
  }
};

struct B : A {
  int b;

protected:
  virtual bool equal_to(A const& other) const {
    if (B const* p = dynamic_cast<B const*>(&other)) {
      return A::equal_to(other) && b == p->b;
    }
    else {
      return false;
    }
  }
};

struct C : A {
  int c;

protected:
  virtual bool equal_to(A const& other) const {
    if (C const* p = dynamic_cast<C const*>(&other)) {
      return A::equal_to(other) && c == p->c;
    }
    else {
      return false;
    }
  }
};
Run Code Online (Sandbox Code Playgroud)