用 new 分配派生类数组的问题 [英] Problem allocating derived class array with new

查看:32
本文介绍了用 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 分配派生类数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆