如何创建一个包含C 中的子类的类的链接列表

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

本文关键字:子类 列表 链接 一个 何创建 创建 包含      更新时间:2023-10-16

例如,在下面的简单示例中,我如何创建一个将信息存储在"父"中的实例下一个节点?

整个代码: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(字符串newname,int newage,parent* n = null) :名称(newname),年龄(newage),下一个(n) { }

您没有立即设置它,这是在要求麻烦。如果您忘了setNext()(现在您只有在列表为空的时候才这样做),然后您有一个悬挂的指针。下一个指针将指向内存中的一个随机位置,而不是null,然后在您去那里时会崩溃。