当程序试图删除我的列表时,我已经为我的类 Word 实现了一个列表,并且检测到了 HEAP CORRUPTION。它在析构函数中进入循环并删除第一个元素,然后当他第二次进入并试图破坏“新”头时,我得到堆损坏错误。我不明白为什么会出错。任何帮助将非常感激。
字.h:
#include <cstring>
class Word
{
protected:
char* word;
char* type;
public:
Word();
Word(char );
Word(char *);
Word(char *, int);
Word(const Word&);
Word& operator=(const Word &);
void setWord(char);
void setWord(char *);
void setWord(char*, int);
void setType(char);
void setType(char*);
void setType(char*, int);
~Word();
};
单词列表.h:
#include "Word.h"
#include <cstdlib>
class WordList
{
public:
struct Node
{
Word data;
Node *next, *prev;
//~Node();
};
Node *head;
Node *tail;
WordList();
~WordList();
void add(Word &d);
};
单词列表.cpp:
#include "WordList.h"
WordList::WordList(void)
{
head = nullptr;
tail = nullptr;
}
WordList::~WordList(void)
{
while(head != nullptr)
{
Node *n = head->prev;
delete head;
head = n;
}
}
void WordList::add(Word &d)
{
Node *n = new Node;
n->data = d; // I overload =, and it copies information from d to data
n->next = head;
if (head!=nullptr)
head->prev = n;
if(head == nullptr){
head = n;
tail = head;
} else
head = n;
}