我只是 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
包含一个纯虚
方法,但它没有被实例化。
main
函数包含 Rectangle
的实例化,它不是纯虚类。所以没有问题
int main()
{
Rectangle * shapes = new Rectangle[10];
for (int i = 0; i < 10; ++i)
shapes[i].draw();
}
-- 我重新发布了 R。 Martinho Fernandes 该帖子的代码接受了答案
关于c++ - 通过父类(super class)的引用访问派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106189/