在C++中是否存在一种惯用的方法来比较对象等价的多态类型?

Ran*_*its 7 c++ polymorphism equality

我有两个多态类型实例的Base*指针,我需要确定引用的对象是否相同.

我目前的方法是首先使用RTTI来检查类型是否相等.如果类型相等,我就调用一个虚拟的is_equivalent函数.

有更惯用的方法吗?

J.N*_*.N. 6

对于大多数派生类,等价只是意味着成员变量具有相同的值

在C++中,这称为"相等",通常使用operator==().在C++中你可以覆盖运算符的含义,可以写:

MyType A;
MyType B;
if (A == B) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

==调用您定义的自定义函数.

我想你想区分平等与身份,这意味着同一个对象(即同一个地址).

您可以将其实现为成员函数或自由函数(来自维基百科):

bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您希望operator==为基类实现,然后执行您正在执行的操作.

更具体地说,它看起来像这样:

class MyBase
{
    virtual ~MyBase(); // reminder on virtual destructor for RTTI
    // ...
private:
    virtual bool is_equal(const MyBase& other);

    friend bool operator ==(const MyBase& a, const MyBase& b); 

    // ...    
};

bool operator ==(const MyBase& a, const MyBase& b)
{
    // RTTI check
    if (typeid(a) != typeid(b))
        return false;
    // Invoke is_equal on derived types
    return a.is_equal(b);
}


class D1 : MyBase
{
    virtual bool is_equal(const Base& other)
    {
        const D1& other_derived = dynamic_cast<const D1&>(other);
        // Now compare *this to other_derived
    }
};

class D2 : MyBase;
{ };


D1 d1; D2 d2;
bool equal = d1 == d2; // will call your operator and return false since
                       // RTTI will say the types are different
Run Code Online (Sandbox Code Playgroud)