繁体   English   中英

如何在C ++中创建包含子类的类的链接列表?

[英]How can I create a linked list of a class that contains child classes in C++?

例如,在下面的简单示例中,如何创建一个“子代”实例,该实例将信息存储在“父代”中,并继续“组”链接列表到下一个节点?

完整代码: https//ideone.com/v7dohX

添加“子代”的示例函数:

void Group::addChild() // Adding an instance of a child class.
{
    Parent *now = bottom, *temp;
    string name = "Jason", gender = "male";
    int age = 21;

    temp == new Child(name, age, gender);

    if (count == 0)
    {
        top = bottom = temp;
        temp->setNext(NULL); // Segmentation fault?
        count++;
    }
}

示例类:

class Parent // Holds the info for each node.
{
    private:
        string name;
        int age;
        string gender; // Will be specified in child class.
        Parent *next;

    public:
        Parent(string newname, int newage)
        {
            name = newname;
            age = newage;
        }

        void setGender(string myGender)  { gender = myGender; }
        void setNext(Parent *n)  { next = n; }
};

class Child : public Parent // Create instances to store name, age, and gender.
{
    public:
        Child(string newname, int newage, string newgender) : Parent(newname, newage)
        {
            setGender(newgender);
        }
};

class Group // Linked list containing all Parent/Child.
{
    private:
        int count;
        Parent *top;
        Parent *bottom;

    public:
        Group()
        {
            count = 0;
            top = bottom = NULL;
        }

        void addChild(); // Defined in the function listed at the top of this post.
};

运行代码时,我遇到了段错误。 如何执行此简单任务?

这段代码有两个重要的缺陷。 正如Joachim所说,您没有分配温度,您进行了比较。

它应该是:

temp =新孩子(姓名,年龄,性别);

但是,您的Parent的构造函数也应该接下来初始化。 也学习初始化器列表语法。 这是一个可能的父构造函数

Parent(字符串newname,int newage,Parent * n = NULL):名称(newname),年龄(newage),next(n){}

您不是立即设置它,这是在麻烦。 如果您忘记了setNext()(现在仅在列表为空时才这样做),那么您将有一个悬空指针。 下一个指针将指向内存中的随机位置,而不是null,并且当您进入那里时,您将崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM