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);
}困惑鏈表
拷貝操作符
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爲指針類型所以我應該可以使用 - >對嗎?
此外,我很困惑,如果這種編碼一般工作。我們已經在課堂上教過複製操作符應該模仿初始化並調用=操作符,但我已經看到一些代碼正好相反。他們的拷貝構造函數被編碼並且賦值操作符調用它。
編輯2:這段代碼給出了段錯誤,但我什麼也看不見。任何在這方面的幫助表示讚賞。
'rhsptr'的確是一個指針,但'rhs'是一個參考,所以你必須使用點運算符,如'RHS。 m_data'。我想這就是你想寫的東西? – roeland 2015-03-19 02:26:23