c++ - 创建模板类的对象后初始化数组时出现分段错误
问题描述
下面是我的链表模板类,我在“LinkedListTemplate.h”中定义它:
template<typename T> class Node{
T data;
Node<T> *next;
public :
void setData(T new_data){
data = new_data;
}
Node<T>* &getNext(){
return next;
}
T getData(){
return data;
}
};
template<typename T> class LinkedList{
private :
Node<T> **head_ref;
public :
LinkedList(){
(*head_ref) = NULL;
}
void insert(T data){
Node<T> *new_node = new Node<T>;
new_node->setData(data);
new_node->getNext() = (*head_ref);
(*head_ref) = new_node;
}
void printList(){
Node<T> *current = (*head_ref);
while(current != NULL){
cout << current -> getData() << " ";
current = current -> getNext();
}
}
Node<T> *getHead() const{
return (*head_ref);
}
void deleteList(){
Node<T> *current = (*head_ref);
Node<T> *next;
while(current != NULL){
next = current -> getNext();
delete current;
current = next;
}
(*head_ref) = NULL;
}
};
所以我想使用这个模板类来创建一个类名 Set 用于管理一组整数它有一个使用给定数组和大小的构造函数,我在“4-5.h”标题中定义这个类
class Set{
private :
LinkedList<int> l;
public :
Set() {}
Set(int a[], int size){
for(int i = 0; i < size; i++)
l.insert(a[i]);
}
~Set(){
l.deleteList();
}
};
因此,在我的主要工作中,当我使用默认构造创建对象以创建对象时,它可以正常工作,但是当我初始化 int 数组时,出现如下分段错误:
int main()
{
Set s1;
cout << s1; // This work fine
int a[] = {2,3} // When i initialize it i got segmentation fault
return 0;
}
解决方案
template<typename T> class LinkedList{
private :
Node<T> **head_ref;
public :
LinkedList(){
(*head_ref) = NULL; // HERE
}
您认为head_ref
我标记的行中指向什么?
你永远不会初始化head_ref
. 所以当你这样做时,(*head_ref)
你正在取消引用一个不指向任何东西的指针。
推荐阅读
- c# - 如何在 C# 中使用树视图更改表单控件?
- monkey-x - 为什么我在最后几行中不断收到“意外令牌'方法'”的语法错误
- bash - 如何将 bash 中的“代码”更改为“代码”。
- python - 访问具有先前非唯一日期的行
- android - 在 remoteMessage.getNotification() 找不到 com.google.android.gms.internal.zzbgl 的类文件
- c# - 垂直翻转 RGBA 图像的快速/优化方式
- python - 使用 Visual Studio 2017 进入 Python 代码 (keras)
- gradle - 如何将多模块项目的最小覆盖规则添加为累积数量
- git - 用另一个替换失败的分支
- python - Python 中的可组合属性更新