Problem allocating derived class array with new(用 new 分配派生类数组的问题)
问题描述
我有一个简单的程序
我认为可以使用 new 来分配派生类对象.此外, v->check() 似乎工作正常.
I thought it is possible to use new to allocate derived class objects. Also, v->check() seems to work fine.
推荐答案
这将创建一个包含两个 MyClass2
对象的数组.它的类型是 MyClass2[2]
.新表达式返回一个指向该数组初始元素的指针,然后将该指针分配给 w
.
This creates an array of two MyClass2
objects. It is of type MyClass2[2]
. The new expression returns a pointer to the initial element of this array and you assign that pointer to w
.
这将 w
视为指向 MyClass
对象数组的指针,not 视为 MyClass2
数组对象.
This treats w
as a pointer to an array of MyClass
objects, not as an array of MyClass2
objects.
您不能将派生类对象数组视为基类对象数组.如果您希望能够使用派生类对象,则需要一个指针数组:
You cannot treat an array of derived class objects as if it were an array of base class objects. If you want to be able to use the derived-class objects, you need an array of pointers:
这篇关于用 new 分配派生类数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!