【发布时间】: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