【发布时间】:2022-11-04 19:14:27
【问题描述】:
我目前正在做一个类项目,我们在其中创建一个链接列表,我们应该创建一个清除列表然后删除它的函数(使用“delete LIST_NAME;”)。我已经按照教授的指示实现了该功能,还强制列表在删除后变为空。该函数在其自身内部工作,但当它返回主函数时,列表会获得一个新值。
这种功能在 C++ 中是不可能的吗?
#include <iostream>
struct Node
{
int val;
Node* next;
};
struct LinkedList
{
int count;
Node* head;
Node* tail;
};
void Clear(LinkedList* list) {
Node* node = list->head;
Node* next = nullptr;
while (node != nullptr) {
next = node->next;
delete node;
node = next;
}
list->head = nullptr;
list->tail = nullptr;
list->count = 0;
}
void Destroy (LinkedList* list) {
Clear(list);
delete list;
list = nullptr;
std::cout << "\n(should be) Destroyed";
}
int main() {
//creating a list element
Node* node = new Node;
node->val = 'a';
node->next = nullptr;
//inserting the element onto list
LinkedList* list = new LinkedList;
list->count = 0;
list->head = node;
list->tail = node;
std::cout << "\nList: " << list;
Destroy(list);
std::cout << "\nList: " << list;
std::cout << "\nEND";
}
这只是我的代码的一个片段,但它说明了我的意思。使用调试器,该列表在函数末尾的值为 0x0,但在主函数中,它被分配了一个新值,如调试器所示。
【问题讨论】:
-
参数是按值传递的,也是指针。
-
在
Destroy函数内部,变量list是一个当地的函数的变量。它的初始值为复制您在通话中使用的那个。修改局部变量不会修改调用中使用的原始值。您需要通过参考. -
你听说过构造函数和析构函数吗?
-
@propelledaviator 你明白我的回答吗?如果不是,请要求澄清。
-
从技术上讲,您已经在显示的代码中使用了两个类:
struct与class相同,但默认为public可见性。
标签: c++