首页 > 解决方案 > 创建模板类的对象后初始化数组时出现分段错误

问题描述

下面是我的链表模板类,我在“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;
}

标签: c++

解决方案


template<typename T> class LinkedList{
private :
    Node<T> **head_ref;
public :
    LinkedList(){
        (*head_ref) = NULL; // HERE
    }

您认为head_ref我标记的行中指向什么?

你永远不会初始化head_ref. 所以当你这样做时,(*head_ref)你正在取消引用一个不指向任何东西的指针。


推荐阅读