【问题标题】:app crash. Templates应用程序崩溃。模板
【发布时间】:2013-11-03 11:31:59
【问题描述】:

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

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

【问题讨论】:

  • 现在是学习使用调试器的好时机。
  • @AlanStokes 并正确标记问题。这与 C 完全无关。

标签: c++ list templates


【解决方案1】:

这段代码肯定有问题:

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

如果 head 为 NULL,则不能执行 head-&gt;next = NULL

【讨论】:

  • 是的。我应该交换它们...这就是访问冲突写入位置 0x00000000 的问题。使用 NULL 指针的原因。谢谢=)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多