Eth*_*han 0 c++ inheritance base-class virtual-destructor
所以我有两个类,一个是抽象的,一个不是.
抽象类是Iterator,具体的是LinkedListIterator.两者的代码都在帖子的底部.
我遇到的问题是下面的代码,我在LinkedListIterator中的析构函数的最后一行说得1错误
undefined reference to `Iterator<int>::~Iterator()'
Run Code Online (Sandbox Code Playgroud)
现在我尝试注释掉虚拟~Iterator()析构函数,没有错误,但我得到一个警告说:
Class '[C@800c1' has virtual method 'remove' but non-virtual destructor
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:我是否需要在抽象Iterator基类中使用虚拟析构函数?我已经读过你应该总是有一个,但在这种情况下,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;
};
Run Code Online (Sandbox Code Playgroud)
相关的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;
}
Run Code Online (Sandbox Code Playgroud)
你的基类应该有一个virtual析构函数,但不是一个纯粹的 virtual析构函数(*).
纯虚函数(即标记为virtual并在= 0其签名后附加后缀的函数)没有实现.但是,基类的析构函数总是需要由子类的析构函数调用,您应该为它提供一个定义(可能是一个空的):
template<class T>
class Iterator {
public:
//~Constructors/Destructors------------//
/*
* Destroys necessary resources.
*/
virtual ~Iterator() { }
...
Run Code Online (Sandbox Code Playgroud)
另请参阅StackOverflow上的此问答以获取相关信息.
(*)如链接的问答中所提到的,可以有一个纯虚拟析构函数(仍然需要定义),但我发现它并不是一个特别好的编程实践.