【发布时间】:2011-11-04 00:01:25
【问题描述】:
我今天去面试,被问到这个有趣的问题。
除了内存泄漏和没有虚拟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();
}
【问题讨论】:
-
除了缺少的分号,你的意思是? (不过,这将是编译时错误,而不是运行时错误)
-
你确定它们都是虚拟的吗?
-
应该是
Shape **它指向一个矩形数组。那么访问应该是shapes[i]->draw(); -
@Tony 祝你好运,随时通知我们:)
-
@AndreyT:代码现在是正确的(最初也是正确的)。
->是编辑犯的错误。