C++ 将链表存储在链表中
C++ Storing a linked list inside a linked list
Class abstractClass
{
int variable1;
string variable2;
public:
abstractClass():variable1(0),variable2(""){};
abstractClass(int variable1,string variable2)
:variable1(variable1),variable2(variable2){};
virtual void show() = 0;
}
class SubClass : public abstractClass // one of the derived class
{
string variable3;
public:
SubClass():variable3(""){};
SubClass(int variable1,string variable2,string variable3)
: abstractClass(variable1,variable2),variable3(variable3){};
void show() {...}
}
class Problem
{
int number;
string name;
LList<abstractClass*>a_list; // linked list of the abstractClass
public:
Problem():number(0),name(""){}; //how to initialize the linked list?
Problem(int number,string name,LList<abstractClass*>a_list)
:number(number),name(name),a_list(a_list){};
void addList();
}
void addProblem(LList<Problem>p_list)
{
p_list.enter(1,Problem(1,"TESTING",...));
// For the ... is to enter a linked list of SubClass objects
}
我的问题是在每个p_list中输入派生类"子类"的多个链表。
我试过了
a_list.enter(1,Subclass(111,"AAA","BBB"));
但这给了我错误。我是否需要对抽象类和子类进行向上转换才能重载子类变量?还是有其他方法可以做到这一点?
以前我尝试输入子类的链表,而不将抽象类的链表放在参数中。
Problem(int number,string name):number(number),name(name){};
LList<Problem> p_list(1,Problem(1,"NAME"));
这没有给我带来任何问题,但我不知道如何在链表中插入链表。
LList<abstractClass*>a_list;
这表示a_list
是指向AbstractClass
的指针列表。
a_list.enter(1,Subclass(111,"AAA","BBB"));
这表示您要将类型为 Subclass
的对象添加到 a_list
。
C++不善于猜测程序员内心深处真正想要的是什么。如果你有一个指针列表,并且你想向它添加一些东西,最好是一个指针。一种方法是
a_list.enter(1, new Subclass(111,"AAA","BBB"));
这将起作用,因为指针到Subclass
可以自动转换为指针到AbstractClass
。
请记住,拥有原始指针列表需要手动管理它们的内存。在这方面,std::unique_ptr<Problem>
列表要好得多。当我们在做这件事时,为什么不使用std::list
而不是自制列表呢?
附加说明。您正在尝试按值传递列表。
addProblem(LList<Problem>p_list)
这可能行不通,因为addProblem
使用列表的副本,并在返回之前将其销毁。您可能希望将其更改为使用按引用调用:
addProblem(LList<Problem>& p_list)
相关文章:
- 反向给定链表中的K节点
- 为什么C中的通用链表中存储的数据已损坏
- 将从格式化文本文件读取的文本数据存储到链表
- C++将存储在链表中的两个大数字相乘
- 相同的地址存储在链表的头部
- 如何将自己的链表实现从存储整数更改为存储个人数据
- 显示来自链表的稀疏矩阵,该链表仅存储了非零元素
- 存储类对象的C++模板链表-未处理的异常访问冲突读取位置
- 使用c++通过文件存储和检索链表
- 为什么链表使用指针而不是将节点存储在节点内部
- 在双链表中,指针不是存储彼此的地址,而是指向相同的位置
- 打印存储在链表中的数据时出现问题
- C++ 将链表存储在链表中
- 将地址和布尔值存储在一个单词中,以实现无锁双链表
- 从文件中读取,存储到链表中,然后再次打印到文件中
- 如何使用链表来存储表,并在表中搜索项
- 为什么这个自定义链表不存储 c++ 中给出的每个元素?
- 将值存储在链表中的结构中
- malloc和heap:用于存储大小和链表信息的额外内存
- 将数据存储到链表中