[英]Is this a deep copy and properly implemented = operator for a C++ Linked List?
現在,我嘗試使用我制作的雙向鏈表類時遇到了一些錯誤。 我對=運算符的實現如下所示:
template <typename T>
Dlist<T>& Dlist<T>::operator=(const Dlist &l)
{
copyAll(l);
return *this;
}
template <typename T>
void Dlist<T>::copyAll(const Dlist &l)
{
node *copyList = new node;
copyList = l.first;
while(copyList){
insertFront(copyList.first->o);
copyList = copyList->next;
}
delete copyList;
}
請注意,o是列表中節點中數據的指針。
我的目的是讓copyAll成為真正的深層副本。 不是嗎? 我的類方法定義在這里有問題嗎? 我是鏈接列表的新手,所以非常感謝您的幫助!
編輯:特別是我遇到的問題是當我創建一個列表並填充它,然后創建一個新列表並將其設置為等於第一個列表時,無論何時我對第二個列表執行操作,它也會更改第一個列表。
EDIT2:這是類本身。 我不允許添加任何其他成員函數:
template <typename T>
class Dlist {
public:
// Operational methods
bool isEmpty();
// EFFECTS: returns true if list is empty, false otherwise
void insertFront(T *o);
// MODIFIES this
// EFFECTS inserts o at the front of the list
void insertBack(T *o);
// MODIFIES this
// EFFECTS inserts o at the back of the list
T *removeFront();
// MODIFIES this
// EFFECTS removes and returns first object from non-empty list
// throws an instance of emptyList if empty
T *removeBack();
// MODIFIES this
// EFFECTS removes and returns last object from non-empty list
// throws an instance of emptyList if empty
// Maintenance methods
Dlist(); // ctor
Dlist(const Dlist &l); // copy ctor
Dlist &operator=(const Dlist &l); // assignment
~Dlist(); // dtor
private:
// A private type
struct node {
node *next;
node *prev;
T *o;
};
node *first; // The pointer to the 1st node (NULL if none)
node *last; // The pointer to the 2nd node (NULL if none)
void makeEmpty();
// EFFECT: called by constructors/operator= to establish empty
// list invariant
void removeAll();
// EFFECT: called by destructor/operator= to remove and destroy
// all list elements
void copyAll(const Dlist &l);
// EFFECT: called by copy constructor/operator= to copy elements
// from a source instance l to this instance
};
基本上, 淺表副本與深表副本之間的區別在於,是僅復制指針本身還是復制指針指向的所有數據。 不要忘記也調用基類並復制其所有成員,以免在派生對象時避免部分初始化!
通常,您要為此目的提供一個副本構造函數 。 賦值運算符類似於復制,但是賦值實際上是在已經構造並且可能已經初始化的對象上完成的。
至於您是否做得好,取決於您的類的實現細節,而您在這里沒有顯示其中的大多數細節。 您顯示的內容看起來不完整。
您可能要考慮使用std::list
直到您對C ++和數據結構更加熟悉,然后再嘗試實現自己的版本。 除了出於好奇或更全面地學習基礎概念之外,如今很少真正需要重新發明輪子。
您說“一些錯誤”。 提出問題時提及那些是有幫助的。
也就是說,請查看copyAll
的前兩行。 第一行分配一個新節點,第二行覆蓋該指針,直到永遠丟失。 也許您的意思是copyList.first = l.first
。 您還需要在while循環內構造新節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.