Home > Back-end >  Methods about recursive destruction of objects
Methods about recursive destruction of objects

Time:01-08

I created a tree node object, the object can link multiple nodes below it, form a tree.
Will probably use it like this:
 
The root Node *=new Node (index, jv);
for (int i=0; i <3; I++)
Node * childLv1=new Node (I, jv);
Root - & gt; AddChild (childLv1);
For (int j=0; J & lt; 2; J++)
Node * childLv2=new Node (j, jv);
ChildLv1 - & gt; AddChild (childLv2);

Delete the root;


 
//h
The class Node
{
Public:
The Node (int, json: : value);
~ the Node ();
Int childCount ();
The child Node * (int index);
Void addChild (Node *);
Void setParam (int index, a double value);
Double getParam (int index);

NODE_TYPE nodeType;
Int index;
Json: : value conf;

Private:
STD: : vectorSTD: : vector _params;
}
//CPP
Node: : ~ Node ()
{
for(int i=0; i The delete child (I);
}

When I delete a node, I want to destroy it at the same time the following
all child nodesI wrote the destructor right??

CodePudding user response:

Generally true
Write a clear function
Void the clear (Node * & amp; X) {
If (x==nullptr)
return;
for(int i=0; iClear (child (I);


}
X=nullptr.
}
~ the Node () {
For (... )
Clear (child (I);

CodePudding user response:

Do not have what problem, you can also use a global method, hand in a recursive delete the root
  • Related