C ++当我创建一个包含链表的类的对象时,为什么我的链接列表模板类失败?

时间:2011-07-14 22:14:56

标签: c++ oop templates linked-list dynamic-allocation

我写了这个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);
}

我无法弄清楚为什么它运行不正确。

2 个答案:

答案 0 :(得分:3)

您需要实现赋值运算符。这个问题从这个函数开始:

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是您的类,并且您没有合适的赋值运算符,因此您只需通过成员(浅)复制成员。

请参阅The Rule of Three

你也应该实现一个交换函数,让你的赋值运算符使用它。

请参阅Copy and Swap Idiom

答案 1 :(得分:2)

在C ++ 03中,本地类不能是模板参数。将theclass移到main之外,它会起作用。

在C ++ 0x中,此限制已被删除。