mercredi 18 mars 2015

Confused about Linked List



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) {}





template<class T>
const LinkedList<T>& LinkedList<T>::operator =(const LinkedList<T>& rhs)
{
if(this != &rhs)
{
if(head != NULL)
{
clear();
}
head = NULL;
Node<T>* rhsptr = rhs.head;
Node<T>* copyptr = new Node<T>;
copyptr->m_data = rhs->m_data;
while(rhs->m_next != NULL)
{
rhsptr = rhsptr->m_next;
copyptr = new Node<T>;
copyptr = copyptr->m_next;
copyptr->m_data = rhsptr->m_data;
}
copyptr->m_next = NULL;

}
return(*this);


}


COPY OPERATOR



template<class T>
LinkedList<T>::LinkedList(const LinkedList<T>& rhs)
{

*this = rhs;
}


When I compile, it says:



linkedlist.hpp:24:25: error: base operand of ‘->’ has non-pointer type ‘const


LinkedList’


copyptr->m_data = rhs->m_data; ^ linkedlist.hpp:25:13: error: base operand of ‘->’ has non-pointer type ‘const


LinkedList’


while(rhs->m_next != NULL)



I'm confused because I declared rhsptr as a pointer type so I should be able to use -> right?


Also, I am confused if this coding works in general. We've been taught in class that the copy operator should just imitate the initialization and call on the = operator but I've seen some codes doing the opposite. Their copy constructor is coded and the assignment operator calls on it.




Aucun commentaire:

Enregistrer un commentaire