英文:
allocating an object of type abstract class c++
问题
我试图创建一个大小为 size_t 的 Media 类型数组,该数组具有一个虚方法,位于 MediaManager 类中,但它给我报了这个错误。
但是我已经在所有子类中实现了这个虚方法,例如 Book 是 Media 的子类。
MediaManager 只是一个充当所有类型的 Media 容器的类。以下是我的 Media 类。
这是 MediaManager 类,我希望在构造函数中初始化指向给定大小的 Media 对象数组的指针。
请问,你能告诉我我做错了什么吗?
我正在尝试在 MediaManager 构造函数中创建 Media 类型的数组,该数组可以容纳任何类型的 Media,然后我可以在进一步的处理中使用该数组。我不能使用 vector,因为问题要求必须使用数组。
英文:
I am trying to make and array of size_t size of type Media which has a virtual method, in class MediaManager
but it is giving me this error
But I have implemented that virtual function in all sub classes, e.g Book is subclass of Media
MediaManager is just a class that act as a container to all type of Media.
here is my Media class
Here is MediaManager class, I want to initialize that Pointer to Media object array in Constructor to given size.
can you tell me please, what am i doing wrong.
I am trying to make array of type Media in MediaManager constructor, that would hold any type of Media,
and then I could use that array for further process.
I cannot use vector because question ask to must use array.
答案1
得分: 0
new Media[size]()
正在请求一个Media数组。但是Media是一个抽象基类,无法被实例化。因此,您需要创建一个指向Media的指针数组,例如new std::unique_ptr<Media>[size]
。然后,您可以用诸如std::make_unique<Book>()
之类的方式填充该数组中的指针。
英文:
new Media[size]()
is asking for an array of Media. But Media is an abstract base class which cannot be constructed. So you need to make an array of pointers to Media, like new std::unique_ptr<Media>[size]
. Then you can populate the pointers in that array with things like std::make_unique<Book>()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论