我在重载operator =时遇到问题。
template <class T>
class Node
{
public:
T m_data; // Data to be stored
Node<T>* m_next; // Pointer to the next element in the list
// Purpose: Default constructor
// Postconditions: next pointer set to NULL
// ---INLINE---
Node() : m_next(NULL) {}
// Purpose: Auxiliaty constructor, construct from parameters
// Postconditions: data and next pointer set to parameters
// ---INLINE---
Node(const T& x, Node<T>* p)
: m_data(x), m_next(p) {}
};
template <class T>
class LinkedList
{
public:
Node<T>* head; // Pointer to the head of the list
// Purpose: Default constructor
// Postconditions: head pointer set to NULL
// ---INLINE---
LinkedList() : head(NULL) {}
// --------
// ---- Big 3 Member Functions ---
// --------
// Purpose: Destructor
// IMPORTANT:: For didactic purposes, the destructor is left empty.
// YOU are expected to implement function clear() to de-allocate the list
// --INLINE
~LinkedList() {}
// 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.
const LinkedList<T>& operator= (const LinkedList<T>& rhs);
// Purpose: copy constructor
// Parameters: rhs is the LinkedList that is to be copied
// Postconditions: this list contains same data values (in same order)
// as in rhs.
LinkedList(const LinkedList<T>& rhs);
以上是给出的。我当前的实现不提供深层复制。
template<class T>
const LinkedList<T>& LinkedList<T>::operator =(const LinkedList<T>& rhs)
{
if(this != &rhs)
{
if(head != NULL)
{
clear();
}
Node<T>* current = rhs.head;
while (current != NULL)
{
insert_front(current -> m_data);
current = current -> m_next;
}
head = current;
}
return(*this);
}