所以我有两个类,一个是抽象的,一个不是。
抽象类是Iterator,具体类是LinkedListIterator。两者的代码都在帖子的底部。
我遇到的问题是代码如下,我在析构函数的最后一行的 LinkedListIterator 中出现 1 个错误说
undefined reference to `Iterator<int>::~Iterator()'
现在我尝试注释掉虚拟 ~Iterator() 析构函数,没有错误,但我收到警告说:
Class '[C@800c1' has virtual method 'remove' but non-virtual destructor
所以我的问题是:抽象迭代器基类中是否需要一个虚拟析构函数?我读过你应该总是有一个,但在这种情况下,LinkedListIterator 中的析构函数只是设置值,它不会释放任何东西......
谢谢!
迭代器代码:
template<class T>
class Iterator {
public:
//~Constructors/Destructors------------//
/*
* Destroys necessary resources.
*/
virtual ~Iterator() = 0;
//~Methods-------------------//
/*
* Informs the user whether there are more elements to be iterated
* over in a List.
*
* @return true if there are more elements to iterate over, false otherwise.
*/
virtual bool hasNext() = 0;
/*
* Gets the next element to iterate over.
*
* @return the next element in the iteration.
*/
virtual T next() = 0;
/*
* Adds an element to the List being iterated over.
*
* @param element the element to add.
* @return true if successful, false otherwise.
*/
virtual bool add(T element) = 0;
/*
* Removes the element last returned by next from
* the List being iterated over.
*
* @return true if successful, false otherwise.
*/
virtual bool remove() = 0;
};
相关 LinkedListIterator 代码(这是一个较长的类):
template<class T>
class LinkedListIterator : public Iterator<T> {
private:
//~Data Fields---------------------------------//
/*
* Pointer to the node that the iterator is currently at.
*/
Node<T>* current;
/*
* Pointer to the LinkedList being iterated through.
*/
LinkedList<T>* list;
/*
* Boolean value indicating whether next has been called since
* the last remove operation.
*/
bool nextCalled;
public:
//~Constructors/Destructors------------------//
/*
* Constructor for LinkedListIterator, takes in a pointer to a Node
* to initialize current to point to (intended to be the head of the
* the LinkedList).
*
* @param theList pointer to the LinkedList being iterated through.
*/
LinkedListIterator(LinkedList<T>* theList) {
current = theList->head;
list = theList;
nextCalled = false;
}
/*
* Destructor, resets pointer values to 0.
*/
~LinkedListIterator() {
current = 0;
list = 0;
}