动态分配类,存在继承问题
我正在尝试动态分配基(学生)类的数组,然后将指向派生(数学)类的指针分配给每个数组槽。我可以通过创建指向基类的单个指针,然后将其分配给派生类来使其工作,但是当我尝试将指针分配给动态分配的基类数组时,它会失败。我已经在下面发布了我正在使用的代码片段。所以基本上我的问题是,为什么动态分配的不工作?
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
I am trying to dynamically allocate an array of base(Student) classes, and then assign pointers to derived(Math) classes to each array slot. I can get it to work by creating a single pointer to the base class, and then assigning that to a derived class, but when I attempt to assign to the pointer to a dynamically allocated array of base classes, it fails. I have posted the fragments of code that I am using below. So basically my question is, why isn't the dynamically allocated one working?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
studentList[0]
不是指针(即Student *
),它是一个对象(即Student
)。听起来有点像你需要的是一个指针数组。在这种情况下,您应该执行以下操作:
在此代码段中,
studentList
的类型是Student **
。因此,studentList[0]
的类型为Student *
。(请注意,在 C++ 中,有更好、更安全的方法来执行此操作,涉及容器类和智能指针。但是,这超出了问题的范围。)
studentList[0]
is not a pointer (i.e. aStudent *
), it's an object (i.e. aStudent
).It sounds a bit like what you need is an array of pointers. In which case, you should do something like:
In this snippet, the type of
studentList
isStudent **
. Therefore, the type ofstudentList[0]
isStudent *
.(Note that in C++, there are better, safer ways to do this, involving container classes and smart pointers. However, that's beyond the scope of the question.)