应用崩溃.模板

app crash. Templates

本文关键字:模板 崩溃 应用      更新时间:2023-10-16

我尝试制作自己的列表容器版本。这样做我遇到了下一个问题。我的应用程序编译得很好,我将实现放在模板类的标头中,但是当我尝试运行我的应用程序时,它崩溃了......我不知道我做错了什么。代码如下:

#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 foundn";
      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;
}

这段代码绝对是有问题的:

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

如果head为 NULL,则无法执行head->next = NULL