C++链表如何使用复制赋值运算符

问题描述 投票:0回答:1

我必须使用复制构造函数和复制赋值运算符来测试链表。

list1 附加了 3 个双打

list2 = list1 复制构造函数进来的地方。

List4 = list3 = list1 是复制赋值运算符的用武之地。

然后 list4 又附加了 1 个 double。

这是我上的课。

// Specification file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H

class NumberList
{
private:
   // Declare a structure for the list
   struct ListNode
   {
      double value;           // The value in this node
      struct ListNode *next;  // To point to the next node
   }; 

   ListNode *head;            // List head pointer

public:
   // Constructor
   NumberList()
        { head = NULL; }
   
   //TO DO: Add the copy constructor 
   NumberList(const NumberList& origObject);

   //TO DO: Add the overloaded assignment operatora
   NumberList& operator=(const NumberList& objToCopy);

   // Destructor
   ~NumberList();
      
   // Linked list operations
   void appendNode(double);
   void insertNode(double);
   void displayList() const;
};
#endif

我有一个简单的复制构造函数,可以完成它必须做的事情。当我执行程序时,构造函数似乎做了必须做的事情。我假设它是因为它只使用了一次复制构造函数。

NumberList::NumberList(const NumberList& origObject){
   
   cout << "copy constructor called." << endl;
   head = new ListNode;
   *head = *(origObject.head);
}

这是我拥有的复制赋值运算符

NumberList& NumberList::operator=(const NumberList& objToCopy){
   cout << "overlaoded operator" << endl;
   if(this != &objToCopy){
      head = new ListNode;
      
      ListNode* nodePtr = new ListNode;
      nodePtr = objToCopy.head;
      nodePtr->next = NULL;

      ListNode* temp = objToCopy.head->next;
      while(temp){
         nodePtr->next = new ListNode;
         nodePtr->next = temp;
         nodePtr = nodePtr->next;
         nodePtr->next = NULL;

         temp = objToCopy.head->next;
      }
   }

   return *this;
}

复制赋值激活后的显示是这样的 list4=list3=list1.

After inserting 5.5 to list4, List1 is: 
1.6

After inserting 5.5 to list4, List3 is: 
0

After inserting 5.5 to list4, List4 is: 
0
5.5

这是什么。它应该看起来像使用操作员后的样子。

After inserting 5.5 to list4, List1 is: 
1.6
4.8
7.9

After inserting 5.5 to list4, List3 is: 
1.6
4.8
7.9

After inserting 5.5 to list4, List4 is: 
1.6
4.8
5.5
7.9

我觉得我越想越不明白我写的代码。所以我基本上一直在写东西,希望它能起作用。


c++ class linked-list copy-constructor deep-copy
1个回答
0
投票

假设

appendNode
已经过测试并且有效,我建议在源列表上进行一个简单的循环,然后在当前列表上调用
appendNode

for (auto* node = objToCopy.head; node; node = node->next)
{
    appendNode(node->value);
}

这个单循环将复制整个源列表。

记得先释放旧列表


为了使

appendNode
更简单、更高效,并且当你想追加一个节点时不必遍历整个列表,我建议你也存储一个指向列表尾部的指针。

© www.soinside.com 2019 - 2024. All rights reserved.