所以我创建了这个 Tree Class ,它的对象是一棵通用树。对于此 Tree 的节点,我还创建了一个 TreeNode 类,其对象将用作我的 Tree 对象的节点。但是,当我对 Tree 类的对象调用 delete 时,删除所有节点后,最终它给出 free() : 输出大小无效。任何人都可以告诉我我的析构函数有什么问题吗?我应该只有一个析构函数吗?或者有什么解决办法吗?请认为我很天真,忽略一些小错误,或者让我知道,以便我纠正它们。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
template <typename T>
class TreeNode{
public:
T data;
vector<TreeNode *> children;
TreeNode(T data){
this -> data = data;
}
~TreeNode(){
for(int i = 0 ; i < children.size() ; i++)
delete children[i];
}
};
template <typename T>
class Tree{
private:
TreeNode<T> *root;
public:
Tree(){
root = NULL;
}
~Tree(){
delete root;
}
void takeInput(){
cout<<"Enter root data"<<endl;
T rootData;
cin>>rootData;
TreeNode<T> *root = new TreeNode<T>(rootData);
queue<TreeNode<T> *> q;
q.push(root);
while(!q.empty()){
TreeNode<T> *front = q.front();
q.pop();
cout<<"Enter child data for "<<front -> data<<endl;
int childData;
cin>>childData;
while(childData != -1){
TreeNode<T> *child = new TreeNode<T>(childData);
front->children.push_back(child);
q.push(child);
cin>>childData;
}
}
this -> root = root;
}
void print(){
cout<<"Printing tree in level order form -: "<<endl;
queue<TreeNode<T> *> q;
q.push(root);
while(!q.empty()){
TreeNode<T> *front = q.front();
q.pop();
cout<<front -> data<<":";
for(int i = 0 ; i < front -> children.size() ; i++){
if(i == front -> children.size() - 1)
cout<<front->children[i]->data;
else
cout<<front -> children[i] -> data<<",";
q.push(front -> children[i]);
}
cout<<endl;
}
}
};
int main(){
Tree<int> t1;
t1.takeInput();
t1.print();
delete &t1;
}
在 TreeNode 析构函数中,删除子向量。子向量可能包含已被树析构函数删除的指针。这可能会导致双重释放错误。为了避免这种情况,Tree 析构函数不得删除子向量,或者 TreeNode 析构函数不得删除子指针。我希望这会有所帮助。