我尝试制作自己的列表容器版本。我遇到了下一个问题。我的应用程序编译得很好,我将实现放在模板类的标题中,但是当我尝试运行我的应用程序时它会崩溃...我不知道我做错了什么。这是代码:
#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;
}
答案 0 :(得分:1)
这段代码肯定是错误的:
if(head == NULL){
toAdd = head;
head->next = NULL;
}
如果head->next = NULL
为NULL,则无法执行head
。