我第一次使用指针,我的代码运行正常,但我需要从另一个 .cpp 文件打印析构函数,但不知道如何执行。
使用这两个函数删除节点后:
bool LList::remove(node* r) {
if (r == NULL || search(r->key) == NULL) {
return false;
}
if (r == head) {
head = head->next;
}
else {
node* prev = getb4(r);
prev->next = r->next;
}
r->next = NULL;
return true;
}
bool LList::drop(int k) {
node* currentNode = search(k);
if (currentNode == NULL || !remove(currentNode))
return false;
node* tmp = currentNode;
while (tmp != NULL) {
currentNode = currentNode->dup;
remove(tmp);
tmp = currentNode;
}
return true;
}
...它使用 main.cpp 中的此函数正确打印了“(key) removed”。
void testDrop(LList& L) {
int key;
cout << "Enter key: ";
cin >> key;
if (L.drop(key))
cout << key << " removed\n";
else
cout << key << " not found in list\n";
}
但是,我还需要它在不更改 main.cpp 的情况下从我的 node.cpp 打印析构函数。这是析构函数:
node::~node() {
if (next) delete next;
if (dup) delete dup;
cout << "NODE DESTRUCT: key=" << key << " data=" << data << endl;
}
任何建议将不胜感激,谢谢。
我假设通过打印你的意思是执行析构函数。在这种情况下,每当您对对象调用 delete 时,编译器都会进行检查以确保对象中存在析构函数,然后执行它。因此,在这种情况下,您将调用delete n;
where n 是您的节点。此外,当您调用 remove node 方法时,您也可以在该节点上调用 delete,只要您确定您的链表和节点析构函数正在适当地处理指针,以免破坏您的列表的顺序,或导致任何其他更严重的问题,例如内存泄漏或悬空指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句