c++ - 通过父类(super class)的引用访问派生类

标签 c++ oop

我只是 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/

相关文章:

c# - 仅在需要时加载类的 byte[] 属性

c++ - 有没有一种优雅的方式来交换 C++ 中的引用?

c++ - 在 XP 上使用 Windows 文件资源管理器时阻止 explorer.exe 任务栏打开

C++:if 内部循环的性能影响

javascript - node js中的面向对象编程

javascript - 在 javascript 中扩展 Promise

python - 如何在 python 中使用继承将多个对象连接成一个对象? (在运行时)

python - dict 对象不可调用 - Python 3

c++ - 带有 shared_ptr 的 RAII

c++ - 无法使对象不可复制