【问题标题】:Copy constructor for a pointer data linked list指针数据链表的复制构造函数
【发布时间】:2017-07-20 06:31:19
【问题描述】:

你能帮我为这个列表写一个复制构造函数吗,注意数据是间接存储的。

     class List {
         private:
         struct Node {
            Data *data;
            Node *next;
         };
         Node *head;
    };

你可以假设你有一个 Data 类的拷贝构造函数。

谢谢。

【问题讨论】:

  • 我宁愿假设你在这方面付出了更多的努力,而不是让别人为你做这件事。我可能错了,但我仍然想这样做。有 数以千计 的复制者示例,其中许多可能会对您有所帮助。你从他们身上学到了什么,到目前为止你做了什么尝试?
  • 这取决于您希望如何管理这些指针的内存。你会通过重新分配来复制这些项目吗?如果您想在复制的列表之间共享这些分配的对象,您会使用智能指针类型,例如shared_ptr?
  • edit您的问题显示what you have tried so far。您应该至少包含您遇到问题的代码的大纲(但最好是minimal reproducible example),然后我们可以尝试帮助解决具体问题。您还应该阅读How to Ask

标签: c++ linked-list


【解决方案1】:

你的类定义需要添加函数签名:

List(const List& list);

参数是您从中复制的列表。

你还需要实现这个功能。

  List::List(const List& list)
  {
    //Iterate through the list parameter's nodes, and recreate the list
    //exactly as it is in the list you passed in.
  }

请注意,您可能不想这样做:

  List::List(const List& list)
  {
    head = list.head;
  }

因为它不是列表的副本,实际上是对 same 列表的第二次引用。

你可以这样调用这个函数:

List thisIsAPremadeList;
List copyOfList(thisIsAPremadeList);

现在 copyOfList 包含 thisIsAPremadeList 拥有的所有内容的深层副本。

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 2016-04-13
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多