408_cpp_classNode

利用class析构函数简化内存回收方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
#define random(x) (rand() % x)
class NewNode
{
public:
NewNode *next = NULL;
int data = 0;
NewNode(int data = 0)
{
this->data = data;
}
~NewNode()
{
cout << "正在释放data为" << data << "的数据" << endl;
delete (next);
cout << "释放完成data为" << data << "的数据" << endl;
}
};

int main()
{
NewNode *head, *node;
head = node = new NewNode();
for (int i = 1; i < 10; i++)
{
node->next = new NewNode(i);
node = node->next;
}
node = head->next;
while (node != NULL)
{
cout << node->data << "\t";
node = node->next;
}
cout<<endl;

delete(head);
}