简体   繁体   中英

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

For example, in the simple example below, how can I create an instance of "Child" that will store the information in "Parent", and continue the "Group" linked list to the next node?

Entire Code: https://ideone.com/v7dohX

Example Function to Add a "Child":

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

Example Classes:

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

When I run my code, I get a segmentation fault. How can I perform this simple task?

There are a couple of important flaws in this code. As Joachim commented, you didnt assign temp, you compared.

It should be:

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

But also, your constructor for Parent should initialize next. Learn initializer list syntax too. Here is a possible parent constructor

Parent(string newname, int newage, Parent* n = NULL) : name(newname), age(newage), next(n) { }

You are not setting it right away, and that is asking for trouble. If you forgot to setNext() (and right now you are only doing so when the list is empty) then you have a dangling pointer. The next pointer will point to a random location in memory, not null, and you will crash when you go there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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