C++ C++;打印析构函数
我是第一次使用指针,我的代码运行正常,但我需要从另一个.cpp文件打印析构函数,我不知道怎么做 使用以下两个功能删除节点后:C++ C++;打印析构函数,c++,pointers,binary-search-tree,destructor,C++,Pointers,Binary Search Tree,Destructor,我是第一次使用指针,我的代码运行正常,但我需要从另一个.cpp文件打印析构函数,我不知道怎么做 使用以下两个功能删除节点后: bool LList::remove(node* r) { if (r == NULL || search(r->key) == NULL) { return false; } if (r == head) { head = head->next; } else { nod
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";
}
void testDrop(LIST&L){
int键;
cout>键;
如果(L.放下(钥匙))
cout我假设打印意味着执行析构函数。在这种情况下,无论何时调用对象上的delete,编译器都会检查以确保
对象中存在一个析构函数,然后执行它。因此在本例中,您将调用delete n;
,其中n是您的节点。此外,当您调用remove node方法时,您也可以在该节点上调用delete,只要您确定您的链表和节点析构函数适当地处理了指针,以免破坏节点您的列表中的顺序,或导致其他更严重的问题,如内存泄漏或悬空指针。< /P>也许您想“代码>删除R;<代码> >使用STD::SyrdypTR,它将调用析构函数,没有现代C++代码应该使用原始代码。pointers@JulianneWright这个名字getb4是什么意思?@VladfromMoscow这是指另一个fu我需要在删除节点时打印析构函数——如果你的代码没有发出delete
调用,析构函数就无法神奇地识别出你“删除了一个节点”。非常感谢!这解决了它。正如我所说的,使用std::shared_ptr,你永远不需要使用原始指针有时需要使用原始指针,特别是如果你正在学习关于数据结构的CS课程,而需要使用原始指针。不太喜欢智能指针链表。递归销毁可能是一个真正的麻烦,因为它需要很长的时间sts。
node::~node() {
if (next) delete next;
if (dup) delete dup;
cout << "NODE DESTRUCT: key=" << key << " data=" << data << endl;
}