【发布时间】:2014-06-08 12:32:40
【问题描述】:
我只是 C++ 和面向对象的东西的初学者。从C过渡。请容忍我的无知。这是继续:
Can a pointer to base point to an array of derived objects?
#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 类包含一个纯虚函数,因此它成为一个抽象类。因此,首先,在为其创建实例时应该存在编译器错误。但我没有得到任何编译器错误。
【问题讨论】:
-
你能把代码贴出来吗?如果没有看到您为编译器提供的内容,我们无法开始回答。
-
对不起,我没有粘贴,因为它在我提到的源链接上..
-
您永远不会创建 Shape 的实例。你觉得你在哪里?
-
顺便说一句:您发布的代码包含一个错误...将
Shape更改为Rectangle...检查接受的答案 -
好的,
Shape * shapes只是创建引用而不实例化类形状,因此没有问题。我说的对吗?