应用崩溃.模板
app crash. Templates
我尝试制作自己的列表容器版本。这样做我遇到了下一个问题。我的应用程序编译得很好,我将实现放在模板类的标头中,但是当我尝试运行我的应用程序时,它崩溃了......我不知道我做错了什么。代码如下:
#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
。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- C++单例模板类使我的程序崩溃
- 赋值运算符在我制作类模板时使代码崩溃
- 编译但每次 #class 模板 c++ 时崩溃
- 调用从 lambda 作为模板参数传递的成员函数指针会崩溃
- 为什么单例模板使我的程序崩溃
- 静态模板成员崩溃
- 应用崩溃.模板
- CLDOC 在模板部分专用化时崩溃
- 类崩溃编译器中的 MSVC 2010 模板化映射
- C++自定义模板LinkedList在添加std::string时崩溃
- clang与gcc运行时的区别:用clang构建的c++类模板在没有复制构造函数的情况下崩溃,用复制构造函数构建的gcc
- 模板化函数在返回值时崩溃
- 模板函数崩溃
- 模板-巨大的目标文件导致链接器崩溃
- 模板程序不断崩溃