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
4

1 回答 1

1

studentList[0]不是指针(即 a Student *),它是一个对象(即 a Student)。

这听起来有点像你需要的是一个指针数组。在这种情况下,您应该执行以下操作:

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

在此代码段中,类型studentListStudent **. 因此, 的类型studentList[0]Student *

(请注意,在 C++ 中,有更好、更安全的方法可以做到这一点,包括容器类和智能指针。但是,这超出了问题的范围。)

于 2010-11-16T23:52:29.843 回答