簡體   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