相关疑难解决方法(0)

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

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

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

c++ pointers

98
推荐指数
3
解决办法
4489
查看次数

标签 统计

c++ ×1

pointers ×1