创建指向另一个类中对象的链表时遇到问题

I am having trouble creating a linked list that points to objects in another class

本文关键字:链表 遇到 问题 对象 另一个 创建      更新时间:2023-10-16

vlist.h

 class Vlist
    {
    public:
        Vlist();
        ~Vlist();
        void insert(string title, string URL, string comment, float length, int rating);
        bool remove();
    private:
        class Node
        {
        public:
            Node(class Video *Video, Node *next)
            {m_video = Video; m_next = next;}
            Video *m_video;
            Node *m_next;
        };
        Node* m_head;
    };

main.cpp

 int main()
    {
    ....blah blah.... (cin the values)
            Array[i] = new Video(title, URL, comment, length, rating);
            Vlist objVlist;
            objVlist.insert(title, URL, comment, length, rating);
    }

vlist.cpp

这就是产生错误的地方

(m_head = new Node(Video, NULL); 

该函数的工作是将指向类视频中对象的指针插入列表中。

 void Vlist::insert(string title, string URL, string comment, float length, int rating)
    {
        Node *ptr = m_head;
        //list is empty
        if(m_head == NULL)
            m_head = new Node(Video, NULL);
        else
        {
            ptr = ptr->m_next;
            ptr = new Node(Video, NULL);
        }
        //sort the list every time this executes
    }

视频.h

这是我试图使用链表指向的类。

class Video
{
public:
    Video(string title, string URL, string comment, float length, int rating);
    ~Video();
    void print();
    bool longer(Video *Other);
    bool higher(Video *Other);
    bool alphabet(Video *Other);
private:
    string m_title;
    string m_url;
    string m_comment;
    float m_length;
    int m_rating;
};

第一次使用堆栈溢出时,不太确定会发生什么。

尝试更改

m_head = new Node(Video, NULL);

m_head = new Node(new Video(title, URL, comment, length, rating), NULL);

这个:

else
{
    ptr = ptr->m_next;
    ptr = new Node(Video, NULL);
}

并不是将新的CCD_ 1添加到列表的头部的正确方式。需要类似的东西:

ptr = new Node(new Video(title, URL, comment, length, rating), NULL);
ptr->m_next = m_head;
m_head = ptr;

"Video"是一个类的名称
您需要创建一个Video实例。

void Vlist::insert(string title, string URL, string comment, float length, int rating)
{
    Video* v = new Video(title, URL, comment, length, rating);
    Node *ptr = m_head;
    if(m_head == NULL)
        m_head = new Node(v, NULL);
    else
    {
        ptr = ptr->m_next;
        ptr = new Node(v, NULL);
    }
    // ...
 }