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

时间:2013-03-12 10:25:56

标签: c++ list

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

    }

video.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;
};

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

2 个答案:

答案 0 :(得分:2)

尝试更改

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);
}

不是将新Node添加到列表头部的正确方法。需要类似的东西:

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

答案 1 :(得分:1)

“视频”是班级的名称 您需要创建一个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);
    }
    // ...
 }