C++ 将链表存储在链表中

C++ Storing a linked list inside a linked list

本文关键字:链表 存储 C++      更新时间:2023-10-16
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)