如何在单链表中重载'='运算符?

时间:2013-02-20 23:34:56

标签: c++ linked-list singly-linked-list

我必须编写一个完整的.hpp实现文件,该文件由基于给定.h文件的函数定义和所有声明和描述组成。我一直在重载operator = function。

linkedlist.h

template <class T>
class LinkedList
{
public:
  T m_data;                  // Data to be stored
  LinkedList<T>* m_next;     // Pointer to the next element in the list
  .
  .
  .
  .
  // Purpose: performs a deep copy of the data from rhs into this linked list
  // Parameters: rhs is linked list to be copied
  // Returns: *this
  // Postconditions: this list contains same data values (in the same order)
  //     as are in rhs; any memory previously used by this list has been
  //     deallocated.
  LinkedList<T>&  operator= (const LinkedList<T>& rhs);
  .
  .
  .
};

到目前为止,这是关于operator =

的.hpp

linkedlist.hpp

template <typename T>
LinkedList<T>& LinkedList::operator= (const LinkedList<T>& rhs)
{
  if(this != rhs) //alias check
  {
    LinkedList* tmp = this -> m_next;
    LinkedList* tmp2 = NULL;
    while(tmp-> != NULL)   //deletes the 'this' linkedlist
    {
      tmp2 = tmp -> m_next;
      delete tmp;
      tmp = tmp2 -> m_next;
    }
    LinkedList* p = rhs -> m_next;
    while(p->m_next != NULL)  //copies the rhs linked list to the 'this' linked list
    {
      m_data = p -> m_data;
      p = rhs -> m_next;
    }
  }
return *this;
}

这是对的吗?

0 个答案:

没有答案