动态分配类,存在继承问题

发布于 2024-10-03 01:09:29 字数 682 浏览 2 评论 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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小情绪 2024-10-10 01:09:29

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++ 中,有更好、更安全的方法来执行此操作,涉及容器类和智能指针。但是,这超出了问题的范围。)

studentList[0] is not a pointer (i.e. a Student *), it's an object (i.e. a Student).

It sounds a bit like what you need is an array of pointers. In which case, you should do something like:

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

In this snippet, the type of studentList is Student **. Therefore, the type of studentList[0] is Student *.

(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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文