2010-11-16 56 views
0

我想動態分配一個基(學生)類的數組,然後指派派生(數學)類的指針到每個數組插槽。我可以通過創建一個指向基類的指針,然後將其分配給派生類,但是當我嘗試將指針指定給動態分配的基類數組時,它會失敗。我已經發布了我在下面使用的代碼片段。所以基本上我的問題是,爲什麼不動態分配的工作?動態分配類,與繼承問題

Student* studentList = new Student[numStudents]; 
    Math* temp = new Math(name, l, c, q, t1, t2, f); 
    studentList[0] = temp;         

/*Fragment Above Gives Error: 

main.cpp: In function âint main()â: 
main.cpp:55: error: no match for âoperator=â in â* studentList = tempâ 
grades.h:13: note: candidates are: Student& Student::operator=(const Student&)*/ 



    Student * testptr; 
    Math * temp = new Math(name, l, c, q, t1, t2, f); 
    testptr = temp 
    //Works 

回答

1
studentList[0]

不是指針(即Student *),它是一個對象(即Student)。

這聽起來有點像你需要的是一個指針數組。在這種情況下,你應該這樣做:

Student **studentList = new Student *[numStudents]; 
Math *temp = new Math(name, l, c, q, t1, t2, f); 
studentList[0] = temp; 

在這個片段中,studentList類型是Student **。因此,studentList[0]的類型是Student *

(請注意,在C++中,有更好,更安全的方式來做到這一點,包括容器類和智能指針。然而,這超出了問題的範圍。)

+0

好吧,我沒有在C看到這++我從某處學習的書,所以我必須審查。 – dubyaa 2010-11-17 00:03:44

+0

'new Student * [numStudents];'爲什麼有指針?這是我不明白的唯一部分。 – dubyaa 2010-11-17 00:04:58

+0

@dubyaa:因爲你需要創建一個項目數組,每個項目都是'Student *'。 – 2010-11-17 00:08:57