【发布时间】:2018-11-27 05:29:34
【问题描述】:
我正在学习面向对象的 C++,并且有一个关于虚拟/纯虚拟和多级继承的问题。
假设我有这样的简单代码:
class Shape
{
virtual int getWidth() = 0;
};
class Rectangle: public Shape
{
private:
int length, width;
public:
Rectangle(_length, _width) { length = _length; width = _width }
int getWidth() { return width }
};
class Square: public Rectangle
{
private:
int length;
public:
Square(int _length):Rectangle(_length, _length) { length = _length };
int getWidth() { return length+1 }; //arbitarily add 1 to distinguish
};
int main()
{
Rectangle* r = new Square(5);
std::cout << r->getWidth << std::endl; //prints 6 instead of 5? It's as if rectangles getWidth is virtual
}
我的理解是多态性将使用“Base”类的功能,除非将getWidth指定为虚拟。我的意思是 r->getArea 的最终调用应该使用 Rectangle 的 getArea 而不是 Square 的 getArea。
在这种情况下,我注意到如果我删除 Shape 中的纯虚拟声明,我们会得到我刚才描述的行为。在基类中拥有一个纯虚函数会自动使该函数的所有定义成为虚函数吗?
【问题讨论】:
标签: c++ inheritance virtual