如何创建一个包含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(字符串newname,int newage,parent* n = null) :名称(newname),年龄(newage),下一个(n) { }
您没有立即设置它,这是在要求麻烦。如果您忘了setNext()(现在您只有在列表为空的时候才这样做),然后您有一个悬挂的指针。下一个指针将指向内存中的一个随机位置,而不是null,然后在您去那里时会崩溃。
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- C++将静态多态类自添加到子类的 constexpr 列表中
- 子类对象列表重新解释为基类对象列表?(C++11).
- SWIG C++ to Python:生成 Python 列表的子类
- C++:从两个包含子类 (typedef) 的列表创建一个列表
- 如何创建一个包含C 中的子类的类的链接列表
- 子类列表"master copies",寻找更好的设计
- 将子类列表转换为超类列表
- 从基类模板化列表中实例化子类对象
- C++传递包含子类元素的类列表
- 迭代子类列表错误
- 对 MFC 文档视图的列表视图进行子类化
- C++ 编译类的子类的时列表
- 如何调用父类类型列表的子类的方法?C++
- 为自定义对象列表使用哪个模型子类/视图
- 排序STL列表的子类
- 保留子类的中心列表,但避免静态实例
- C++不同子类的链接列表