【问题标题】:C++ doubly linked list: How to show that Destructor is implemented correctlyC++ 双向链表:如何显示 Destructor 已正确实现
【发布时间】:2018-10-16 02:30:26
【问题描述】:

基本上,我已经创建了一个双向链表,现在需要证明析构函数已在 main.cpp(int main)中实现和测试。

在作业中建议我应该创建一个函数,并放置一个 cout 语句,该语句在每个节点被删除之前输出它的地址。我不知道该怎么做。

到目前为止,我已经创建了一个这样的函数:

void cList() {
    DoublyLinkedList a
    cout << "ex: 0 1 2 3" << endl;
    for (unsigned i = 0; i < 4; i++) {
        a.push_back(i);
    }
    cout << "Display in function: ";
    a.display();
    cout << endl;

    //this shows the addresses of each node
    cout << "delete addresses: " << endl;
    for (it = del.begin(); it!=del.end(); ++it) {
        cout << &it << endl;
    }
}

我知道当列表超出范围时,将调用析构函数。我在 ~DoublyLinkedList 中有一个 cout 语句,上面写着“调用了析构函数”。当我这样做时,会在显示地址后输出“调用析构函数”语句。但是如何通过在删除之前显示地址来满足要求?谢谢。

样本输出:

delete addresses:
0x7ffeb484d300
0x7ffeb484d300
0x7ffeb484d300
0x7ffeb484d300
Destructor Called

【问题讨论】:

  • 你有显示列表元素的功能吗?

标签: c++ destructor


【解决方案1】:

您的构造函数可以在创建对象时输出它:

Node::Node()
{
    std::cout << "Creating node: " << this << std::endl;
}

那么你的析构函数可以输出相反的结果

Node::~Node()
{
    std::cout << "Destroying node: " << this << std::endl;
}

那么你不需要delete main 中的任何东西。您只需要确保 DoublyLinkedList 的析构函数通过并销毁所有 Node 对象。然后,当DoublyLinkedList a 超出范围时,您将看到析构函数的输出。

【讨论】:

  • 你打字太快了,先生。
  • 谢谢!我没有 ~Node 函数,但我按照你在 ~DoublyLinkedList 中的建议做了。这就是我所做的(抱歉格式化,仍然需要这个站点):DoublyLinkedList::~DoublyLinkedList() { IntNode* here = head; while(here != NULL) { cout
【解决方案2】:

你可以把这部分放到析构函数中:

cout << "delete addresses: " << endl;
    for (it = del.begin(); it!=del.end(); ++it) {
        cout << &it << endl;
    }

所以函数结束时会自动显示删除节点的输出。

//This is assuming you aren't using any sentinel head/tail pointers.
~DoublyLinkedList() {
        cout << "delete addresses: " << endl;

        Node* nextNode = nullptr;

        while(headPtr) {
            nextNode = headPtr->next;
            cout << headPtr << endl;
            delete headPtr;
            headPtr = nextNode;
        }
        cout << "Destructor Called" << endl;
    }

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2012-05-10
    • 2015-05-16
    • 2021-11-18
    • 2011-06-03
    • 2018-03-14
    • 2013-10-29
    • 2016-06-10
    相关资源
    最近更新 更多