0xC00000005未实例化指针错误



为了更好地理解C++,我正在开发一个单链列表类,但我遇到了困难。

遗憾的是,这个标题几乎是我所能理解的错误。这里和这里似乎都提出了一些答案,但我一直试图实施这些答案。

main.cpp:

#include <iostream>
#include <string>
#include "LinkedList.h"
#include "Node.h"
using namespace std;
int main()
{
    LinkedList<string> moo2;
    moo2.insertAtFront("one");
    moo2.insertAtFront("two");
    moo2.insertAtFront("three");
    moo2.insertAtFront("four");
    cout<<moo2.toString() << endl;
    cin.ignore(1);
    return 0;
}

LinkedList.h:

#pragma once
#include "Node.h"
#include <string>
#include <sstream>
template <class type>
class LinkedList
{
private:
    int size;
    node<type> *head; 
public:
    LinkedList()
    {
        head = NULL;
        //head = (node<type>*)malloc(sizeof(node<type>));
        size = 0;
    }
    /*LinkedList(const LinkedList<type> &x)
    {
        head = NULL;
        //head = (node<U>*)malloc(sizeof(node<U>));
        size = 0;
    }*/
    bool insertAtFront(type obj)
    {
        node<type> *temp;
        temp = (node<type>*)malloc(sizeof(node<type>));
        temp->data = obj;
        temp->next = head;
        head = temp;
        size++;
        return true;
    }
    std::string toString()
    {
        std::stringstream value;
        node<type> *i = head;
        while(i != NULL)
        {
            value << i->data;
            if(i->next != NULL)
                value << ", ";
            i = i->next;
        }
        return value.str();
    }
};

node.h:

#pragma once
#include <string>
template <class type>
struct node
{
    type data;
    node *next;
    node() 
    {
        data = NULL;
        next = NULL;
        //data = new type();
        //next = (node<U>*)malloc(sizeof(node<U>));
    }
    node(type)
    {
        data = type;
        next = NULL;
        //next = (node<U>*)malloc(sizeof(node<U>));
    }
    node(type, node *)
    {
        data = type;
        next = next2;
    }
    /*node(const node &x)
    {
        data = new type(x->data);
        next = new x->next;
    }*/
};

我不知道(无论如何,我都不确定)是哪个变量造成了错误,因为它可能是LinkedList的*head(或head->data或head->next),也可能是nodes*next。

然而,真正奇怪的是,对于我迄今为止尝试过的任何其他参数化类型(int、double、long、char、char*),代码都运行得非常好。事实上,我甚至可以使用char*来实现与字符串列表相同的目标。尽管如此,我还是想知道为什么我会遇到这些问题,以及可以采取的任何措施来解决它。

使用new而不是malloc

malloc只是为给定的类型或大小分配内存,它不会调用构造函数。

最新更新