2016-02-28 38 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]。 –