【问题标题】:Accessing a derived class through the reference of super class通过超类的引用访问派生类
【发布时间】: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 只是创建引用而不实例化类形状,因此没有问题。我说的对吗?

标签: c++ oop


【解决方案1】:

确实Shape 包含一个pure virtual 方法,但它没有被实例化。

main 函数包含Rectangle 的实例化,它不是纯虚拟类。所以没有问题

int main()
{
    Rectangle * shapes = new Rectangle[10];
    for (int i = 0; i < 10; ++i)
        shapes[i].draw();
}

-- 我已经重新发布了R。 Martinho Fernandes 该帖子中的代码已接受答案

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    相关资源
    最近更新 更多