【问题标题】:What is the point of initializing a base class object as a derived class object将基类对象初始化为派生类对象有什么意义
【发布时间】:2018-04-29 07:06:26
【问题描述】:

如果我想初始化一个类Square

class Square : public Rectangle {
    public Square(int length)
    {
        this->length = length;
        this->width = length;
    }
}

派生自一个类Rectangle

class Rectangle {
    protected int length, width;

    public Rectangle(int length, int width)
    {
        this->length = length;
        this->width = width;
    }

    public int getArea() { return length * width; }
}

我会这样做

Square * s = new Square(5);
cout << s->getArea() << endl;

这样做有什么好处

Rectangle * r = new Square(5);
cout << r->getArea() << endl;

而是将对象初始化为基类对象?

【问题讨论】:

  • 在面向对象语言中搜索继承。

标签: class interface polymorphism derived-class base-class


【解决方案1】:

您有一个接口和该接口的一个实现。这是继承多态性如何协同工作的一部分。

Rectangle *r = new Square 仅在 Square 派生自 Rectangle 时有效。任何属于Rectangle 后代的对象都可以分配给Rectangle* 指针。

假设您的所有代码需要一个 Rectangle* 指针来完成它的工作。代码不需要关心它是否对内存中的Square 对象进行操作。也许您必须根据运行时的用户输入或某些业务规则等做出该决定。多态性允许这样做。 接口 确保所需的Rectangle 功能可用,以及如何使用它。编译器负责相应地委派给实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多