C ++类实现接口,接口具有采用任何实现该接口的类的方法
c++ class implementing interface, interface has method taking any class implementing that interface
我正在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 !=.
}
相关文章:
- 如何从实现接口的模板化类实例访问结构
- 传递实现特定接口的类
- 如何在C++中实现接口
- C++ 使用接口和默认实现继承
- unique_ptr实现接口时对已删除函数的引用
- C++接口实现和子类化对象识别
- 接口实现和私有继承之间的交互
- Pimpl习惯用法、单独的接口/实现文件和多个虚拟继承.如何
- 定义大量的接口实现
- cpp文件中的纯虚拟接口实现
- 如何使用接口实现回调
- 继承接口实现
- 如何在C++中编写类java参数级接口实现
- 具有其他默认参数的接口实现
- Mixin和接口实现
- 如何在许多类中重用接口实现
- Emscripten Javascript接口实现
- 获取Firefox内置组件的接口实现
- c++中的头文件和Java中的抽象类/接口实现是相同的想法,这是正确的吗?
- C++中的接口+实现:代码不执行