C ++类实现接口,接口具有采用任何实现该接口的类的方法

c++ class implementing interface, interface has method taking any class implementing that interface

本文关键字:接口 实现 任何 方法      更新时间:2023-10-16

我正在C++中实现自己的链表。下面的代码用于链表的迭代器部分。

class Iterator
{
public:
    virtual bool operator== (const Iterator &rhs) const = 0;
};
class LinkedListIterator : public Iterator
{
public:
    int fieldOnlyLinkedListIteratorHas;
    bool operator== (const Iterator &rhs) const
    {
        return fieldOnlyLinkedListIteratorHas == rhs.fieldOnlyLinkedListIteratorHas;
    }
};

我想有一个Iterator接口,其中包含许多(未来(迭代器也可以实现的一些常用方法。

从代码中,您可以猜到,rhs变量没有该字段,因此代码不会编译。但是我应该把它改成什么?此代码也不起作用:

bool operator== (const Iterator &rhs) const
{
    LinkedListIterator &rhs2 = (LinkedListIterator)rhs;
    return fieldOnlyLinkedListIteratorHas == rhs2.fieldOnlyLinkedListIteratorHas;
}

这也不是:

bool operator== (const LinkedListIterator &rhs) const
{
    return fieldOnlyLinkedListIteratorHas == rhs.fieldOnlyLinkedListIteratorHas;
}

从那以后,LinkedListIterator类是抽象的。

为了在 Java 中解决这个问题,我会使用 instanceof 但是如何在C++中做到这一点?

dynamic_cast<>将提供与Java实例最等效的功能。这要求编译器启用 RTTI

但是,需要使用dynamic_cast<>通常表明设计可以改进。

bool operator== (const Iterator &rhs) const
{
    const LinkedListIterator *rhs2 = dynamic_cast<const LinkedListIterator *>(&rhs);
    if (rhs2) {
        return fieldOnlyLinkedListIteratorHas == rhs2->fieldOnlyLinkedListIteratorHas;
    }
    return false; // Is not an instance of LinkedListIterator, therefore must be !=.
}