2013-11-03 40 views
0

我试图让我自己的列表container.I得到下一个问题,这样做。我的应用编译得很好,我把实现放在模板类的头文件中,但是当我尝试运行我的应用程序时它崩溃了......我不知道我做错了什么。这里的代码:应用崩溃。模板

#ifndef _CH10EX8_ 
#define _CH10EX8_ 
#include <iostream> 
#include <cstring> 

template<typename T> 
class List{ 
private: 
    struct Item{ 
     Item* next; 
     int index; 
     T data; 
}; 

    Item* head; 

public: 
    List(); 
    ~List(); 
    void addItem(const T&); 
    void showList()const; 
    T& getItem(int)const; 
}; 


template<typename T> 
List<T>::List() 
{ 
    head = NULL; 
}; 

template<typename T> 
List<T>::~List() 
{ 
    Item* current = head; 
    Item* prev; 
    while(current->next != NULL){ 
    prev = current; 
    current = current->next; 
    delete prev; 
    } 
    delete current; 
    delete head; 
} 

template<typename T> 
void List<T>::addItem(const T& val){ 
    static int index = 0; 
    Item* toAdd = new Item; 
    toAdd->data = val; 
    toAdd->index = index; 
    ++index; 

    if(head == NULL){ 
    toAdd = head; 
    head->next = NULL; 
    } 
    else{ 
    Item* current = head; 
    while(current->next != NULL) 
     current = current->next; 

    current->next = toAdd; 
    toAdd->next = NULL; 
    } 
} 

template<typename T> 
void List<T>::showList()const{ 
    Item* current = head; 

    while(current->next != NULL) 
    std::cout << "Data: " << current->data 
      << "At index: " << current->index << std::endl; 
} 
template<typename T> 
T& List<T>::getItem(int id)const{ 
    Item* current = head; 
    if(current->index != id){ 
    while(current->next->index != id) 
     { 
    if(current->next == NULL){ 
     std::cout << "Item at index " << id << "not found\n"; 
     break; 
    } 
     } 
    return current->data; 
    } 
    else 
    return current->data; 
} 

#endif 

这是头。这里是我的主:

#include "ch10ex8.h" 

int main(int argc,char** argv){ 

    List<double> m_list; 

    for(double id = 0; id < 50.0; ++id) 
    m_list.addItem(id); 

    m_list.showList(); 

    std::cout << "Found item: " << m_list.getItem(20) << std::endl 
     << "At index: " << 20 << std::endl; 
    return 0; 
} 
+3

现在将是学习使用调试器的好时机。 –

+0

@AlanStokes并正确标记问题。这与C完全无关。 – Manu343726

回答

1

这段代码绝对是越野车:

if(head == NULL){ 
    toAdd = head; 
    head->next = NULL; 
    } 

你不能这样做head->next = NULL如果head为NULL。

+0

是的。我应该交换他们...这是问题访问冲突写入位置0x00000000。使用NULL指针的原因。谢谢=) –