【发布时间】:2011-08-08 22:17:14
【问题描述】:
现在我正在尝试使用我创建的双向链表类时遇到了一些错误。我对 = 运算符的实现如下所示:
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 是指向 List 中节点中数据的指针。
我的意图是让 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
};
【问题讨论】:
-
我不认为该代码可以编译,您将
copyList用作指针(->next)和引用(.first)。最后的删除没有意义,copyList应该始终为空。 -
它确实可以编译,但它没有做它应该做的事情。
标签: c++ class operator-overloading linked-list