使用new分配派生类数组的问题 [英] Problem allocating derived class array with 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<< 调用w [0] .check\\\
; w [0] .check();
std :: cout<< calling v-> check\\\
; v-> check();
std :: cout<< call w [1] .check\\\
; w [1] .check();
}
$ g ++ a.cpp
$ ./a.out
调用w [0] .check
在MyClass2中
调用v-> check
Inside MyClass2
调用w [1] .check
分段错误
我认为可以使用new来分配派生类对象。此外,v-> check()似乎工作正常。
w = new MyClass2 [2];
这将创建两个 MyClass2
对象的数组。它是 MyClass2 [2]
的类型。新表达式返回指向此数组的初始元素的指针,并将该指针分配给 w
。
w [1] .check();
这会将 w
数组 MyClass
对象,不作为 MyClass2
对象的数组。
您不能将派生类对象数组看作是基类对象数组。如果你想要使用派生类对象,你需要一个指针数组:
MyClass ** w = new MyClass * [2];
w [0] = new MyClass2;
w [1] = new MyClass2;
I have a simple program
$ cat a.cpp
#include <iostream>
class MyClass {
public:
virtual void check() {
std::cout << "Inside MyClass\n";
}
};
class MyClass2: public MyClass {
public:
int* a;
virtual void check() {
std::cout << "Inside MyClass2\n";
}
};
int main() {
MyClass *w, *v;
w = new MyClass2[2];
v = new MyClass2;
std::cout << "Calling w[0].check\n"; w[0].check();
std::cout << "Calling v->check\n"; v->check();
std::cout << "Calling w[1].check\n"; 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
I thought it is possible to use new to allocate derived class objects. Also, v->check() seems to work fine.
w = new MyClass2[2];
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();
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分配派生类数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!