基指针可以指向派生对象的数组吗? [英] Can a pointer to base point to an array of derived objects?

查看:114
本文介绍了基指针可以指向派生对象的数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天去面试一个工作面试,并给了这个有趣的问题。

I went to a job interview today and was given this interesting question.

除了内存泄漏和事实,没有虚拟dtor,为什么这个代码崩溃?

Besides the memory leak and the fact there is no virtual dtor, why does this code crash?

#include <iostream>

//besides the obvious mem leak, why does this code crash?

class Shape
{
public:
    virtual void draw() const = 0;
};

class Circle : public Shape
{
public:
    virtual void draw() const { }

    int radius;
};

class Rectangle : public Shape
{
public:
    virtual void draw() const { }

    int height;
    int width;
};

int main()
{
    Shape * shapes = new Rectangle[10];
    for (int i = 0; i < 10; ++i)
        shapes[i].draw();
}


推荐答案

您已经分配了 Rectangles 的数组,并且存储了指向 shapes 中的第一个的指针。当您执行 shapes [1] 时,您要取消引用(shapes + 1)。这不会给你一个指向下一个 Rectangle 的指针,而是一个指向下一个 Shape 的指针推测数组 Shape 。当然,这是未定义的行为。

You cannot index like that. You have allocated an array of Rectangles and stored a pointer to the first in shapes. When you do shapes[1] you're dereferencing (shapes + 1). This will not give you a pointer to the next Rectangle, but a pointer to what would be the next Shape in a presumed array of Shape. Of course, this is undefined behaviour. In your case, you're being lucky and getting a crash.

使用指向 Rectangle 的指针可以建立索引

Using a pointer to Rectangle makes the indexing work correctly.

int main()
{
   Rectangle * shapes = new Rectangle[10];
   for (int i = 0; i < 10; ++i) shapes[i].draw();
}

如果你想有不同种类的 Shape s在数组中,并使用它们多态,你需要一个指针到Shape。

If you want to have different kinds of Shapes in the array and use them polymorphically you need an array of pointers to Shape.

这篇关于基指针可以指向派生对象的数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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