我编写了这个LinkedList模板类,它还没有完成——我还需要添加安全特性和更多的方法。现在我需要它做什么它就做什么。但在某些情况下,它失败了,我不知道为什么。
template<class data_type> class LinkedList {
private:
struct Node {
data_type data;
Node* prev;
Node* next;
Node() : prev(NULL), next(NULL) {}
};
Node* head;
Node* GetLastNode() {
Node* cur = head;
while (cur->next != NULL)
cur = cur->next;
return cur;
}
public:
LinkedList() {
head = new Node;
head->prev = head;
head->next = NULL;
}
LinkedList(LinkedList<data_type> &to_copy) {
head = new Node;
head->prev = head;
head->next = NULL;
for (int i = 1; i <= to_copy.NumberOfItems(); i++) {
this->AddToList(to_copy.GetItem(i));
}
}
~LinkedList() {
DeleteAll();
delete head;
head = NULL;
}
void AddToList(const data_type data) {
Node* last = GetLastNode();
Node* newnode = last->next = new Node;
newnode->prev = last;
newnode->data = data;
}
void Delete(const unsigned int position) {
int currentnumberofitems = NumberOfItems();
Node* cur = head->next;
int pos = 1;
while (pos < position) {
cur = cur->next;
pos++;
}
cur->prev->next = cur->next;
if (position != currentnumberofitems)
cur->next->prev = cur->prev;
delete cur;
}
void DeleteAll() {
Node* last = GetLastNode();
Node* prev = last->prev;
while (prev != head) {
delete last;
last = prev;
prev = last->prev;
}
head->next = NULL;
}
data_type GetItem(unsigned int item_number) {
Node* cur = head->next;
for (int i = 1; i < item_number; i++) {
cur = cur->next;
}
return cur->data;
}
data_type* GetItemRef(unsigned int item_number) {
Node* cur = head->next;
for (int i = 1; i < item_number; i++) {
cur = cur->next;
}
return &(cur->data);
}
int NumberOfItems() {
int count(0);
Node* cur = head;
while (cur->next != NULL) {
cur = cur->next;
count++;
}
return count;
}
};
我在问题中陈述了我的问题,下面是一个例子:
class theclass {
public:
LinkedList<int> listinclass;
};
void main() {
LinkedList<theclass> listoftheclass;
theclass oneclass;
oneclass.listinclass.AddToList(5);
listoftheclass.AddToList(oneclass);
cout << listoftheclass.GetItem(1).listinclass.GetItem(1);
}
我不明白为什么它不能正常运行。
您需要实现一个赋值操作符。问题从这个函数开始:
void AddToList(const data_type data) {
Node* last = GetLastNode();
Node* newnode = last->next = new Node;
newnode->prev = last;
newnode->data = data; <---------------------------- Right there
}
因为data_type是你的类,而你没有一个合适的赋值操作符,你只是得到一个成员一个成员的(浅)复制。
参见"三原则"
你可能还应该实现一个交换函数,并让你的赋值操作符使用它。
参见复制和交换习语
在c++ 03中,局部类不能作为模板参数。将theclass
移到main
之外,它将工作。