动态创建子类和父类继承

问题描述

为什么不允许这样 Rectangle *test = new Shape();

但是你可以 Shape *testRect = new Rectangle();

我假设第一个被允许,因为孩子继承了基础,所以你可以从一个矩形创建一个形状。而且 Shape 不能动态创建 Rectangle,因为它对继承它的类一无所知。

// Base class
    class Shape {
       public:
          void setWidth(int w) {
             width = w;
          }
          void setHeight(int h) {
             height = h;
          }
        int getShape() { 
             return (width *1000); 
          }
       protected:
          int width;
          int height;
    };
    // Derived class
    class Rectangle: public Shape {
       public:
          int getArea() { 
             return (width * height); 
          }
    };
    int main(void) {
        // not does not work
       //Rectangle *test = new Shape();
        // allowed
       Shape *testRect = new Rectangle();
       return 0;
    }

解决方法

Shape *testRect = new Rectangle();

是允许的,因为每个 Rectangle 一个 Shape

Rectangle *test = new Shape();

无法工作,因为 Shape 不是 Rectangle


你下面的论证是完全正确的。

我假设第一个被允许,因为孩子继承了基础,所以你可以从一个矩形创建一个形状。而且 Shape 不能动态创建 Rectangle,因为它对继承它的类一无所知。

您可能只是混淆了什么是什么。基本上任何指向 Rectangle 的指针(如从 new Rectangle() 返回的指针)也指向 Shape,因此第一个赋值是有效的。

但是new Shape())返回的指针没有指向任何Rectangle,所以第二次赋值无效。

,

你应该学习更多关于 C++ 继承的知识。

https://www.learncpp.com/cpp-tutorial/basic-inheritance-in-c/

基类指针可以指向派生类对象,但反过来不行。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...