Problem allocating derived class array with new(用 new 分配派生类数组的问题)
问题描述
我有一个简单的程序
$ cat a.cpp
#include <iostream>
class MyClass {
public:
virtual void check() {
std::cout << "Inside MyClass
";
}
};
class MyClass2: public MyClass {
public:
int* a;
virtual void check() {
std::cout << "Inside MyClass2
";
}
};
int main() {
MyClass *w, *v;
w = new MyClass2[2];
v = new MyClass2;
std::cout << "Calling w[0].check
"; w[0].check();
std::cout << "Calling v->check
"; v->check();
std::cout << "Calling w[1].check
"; w[1].check();
}
$ g++ a.cpp
$ ./a.out
Calling w[0].check
Inside MyClass2
Calling v->check
Inside MyClass2
Calling w[1].check
Segmentation fault
我认为可以使用 new 来分配派生类对象.此外, v->check() 似乎工作正常.
I thought it is possible to use new to allocate derived class objects. Also, v->check() seems to work fine.
推荐答案
w = new MyClass2[2];
这将创建一个包含两个 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[1].check();
这将 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:
MyClass** w = new MyClass*[2];
w[0] = new MyClass2;
w[1] = new MyClass2;
这篇关于用 new 分配派生类数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 new 分配派生类数组的问题


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01