gpt4 book ai didi

c++ - C++ 中的继承和虚拟析构函数问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:11 25 4
gpt4 key购买 nike

所以我有两个类,一个是抽象的,一个不是。

抽象类是Iterator,具体类是LinkedListIterator。两者的代码都在帖子的底部。

我遇到的问题是下面的代码,我的 LinkedListIterator 出现 1 个错误在析构函数的最后一行说

undefined reference to `Iterator<int>::~Iterator()'

现在我尝试注释掉虚拟的 ~Iterator() 析构函数,没有错误,但我收到一条警告:

Class '[C@800c1' has virtual method 'remove' but non-virtual destructor

所以我的问题是:抽象 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;
};

相关的 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;
}

最佳答案

你的基类应该有一个virtual 析构函数,但不是 virtual 析构函数 (*)。

纯虚函数(即标记为 virtual 并在其签名后附加 = 0 后缀的函数)没有实现。然而,基类的析构函数总是需要被子类的析构函数调用,你应该为它提供一个定义(可能是一个空的):

template<class T>
class Iterator {

public:
//~Constructors/Destructors------------//
/*
* Destroys necessary resources.
*/
virtual ~Iterator() { }
...

另见 this Q&A on StackOverflow 获取相关信息。

(*) 如链接的问答中所述,可以有一个纯虚拟析构函数(仍然需要定义),但我认为这不是一个特别好的编程实践。

关于c++ - C++ 中的继承和虚拟析构函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14965928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com