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 ОПЕРАТОРА
template<class T>
LinkedList<T>::LinkedList(const LinkedList<T>& rhs)
{
*this = rhs;
}
Когда я компилирую, он говорит:
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)
Я смущен, потому что я объявил rhsptr как тип указателя поэтому я должен быть в состоянии использовать -> правильно?
Кроме того, я смущен, если это кодирование работает в целом. Мы учили в классе, что оператор копирования должен просто имитировать инициализацию и вызвать оператор =, но я видел, как некоторые коды делают наоборот. Их конструктор копирования закодирован, и оператор присваивания вызывает его.
EDIT 2: Этот блок кода дает ошибку сегмента, но я ничего не вижу. Любая помощь на этом фронте ценится.
'rhsptr' действительно является указателем, но' rhs' является ссылкой, так что вы должны использовать оператор точки, как в 'РИТ. m_data'. Наверное, это то, что ты хотел написать? – roeland