2016-02-28 71 views
-2
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_LISTC++链表中存储一个链表

我已经试过内部进入派生类的子类'的多个链接列表

a_list.enter(1,Subclass(111,"AAA","BBB")); 

但这给了我错误。为了重载子类变量,我需要为abstractClass和Subclass做上传吗?还是有另一种方法来做到这一点?

此前,我尝试输入子类的链接列表,而不在参数中放入抽象类的链接列表。

Problem(int number,string name):number(number),name(name){}; 
LList<Problem> p_list(1,Problem(1,"NAME")); 

这给了我没有问题,但我不知道如何在链表中插入链表。

+0

也许更有意义的名称是一个好主意 –

+0

除了列出了问题,这个'类的类:公共Student'说,'Classes'是一种'学生'。看起来并不适合我。一个学生可能*参加*课,但他们真的不是一回事。 –

回答

0
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")); 

这会起作用,因为指针TO- Subclass可以自动转换为指针,TO-AbstractClass

请记住,拥有原始指针列表需要手动管理其内存。在这方面,std::unique_ptr<Problem>的列表要好得多。虽然我们在这,但为什么不使用std::list而不是自制列表?

补充说明。您正试图通过价值传递您的列表。

addProblem(LList<Problem>p_list) 

这可能是不会用的工作与你的列表的副本做工精良,为addProblem,并在返回之前摧毁它。你可能想改变它参考使用电话:

addProblem(LList<Problem>& p_list) 
+0

免责声明:答案是基于我颇受教育的猜测,但这是一个猜测。为了消除猜测,在你的问题中加入[mcve]。 –

+0

这已经解决了我关于a_list链接列表指针的问题但是我在问题中提到的其他问题之一是在链表的一个数据中添加链表。 (1,新的子类(111,“AAA”,BBB“)); 将其添加到p_list = p_list中。输入(1,“TESTING,a_list),我需要调用什么样的函数? 例如:addProblem(LList &p_list,LList a_list) –

+0

不清楚你的其他问题是什么。你会得到任何错误或意外的输出?请阅读[mcve]。 –