指向基的指针可以指向派生对象数组吗?

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

问题描述

我今天去面试了,被问到这个有趣的问题.

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 并多态地使用它们,你需要一个 指针 到 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.

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

上一篇:指向引用的指针和指向指针的引用之间的区别 下一篇:为什么 NULL 指针在 C 和 C++ 中的定义不同?

相关文章

最新文章