【发布时间】:2012-03-03 10:42:22
【问题描述】:
我正在阅读 GoF 的一本关于设计模式的书 - online link。
在本书的适配器模式中,在示例代码部分,我遇到了这个特定的代码:
class TextView {
public:
TextView();
void GetOrigin(Coord& x, Coord& y) const;
void GetExtent(Coord& width, Coord& height) const;
virtual bool IsEmpty() const;
};
这个类TextView被TextShape私有继承如下:
class TextShape : public Shape, private TextView {
public:
TextShape();
virtual void BoundingBox(
Point& bottomLeft, Point& topRight
) const;
virtual bool IsEmpty() const;
virtual Manipulator* CreateManipulator() const;
};
然后在这个void TextShape::BoundingBox函数中如下:
void TextShape::BoundingBox (
Point& bottomLeft, Point& topRight
) const {
Coord bottom, left, width, height;
GetOrigin(bottom, left); //How is this possible? these are privately inherited??
GetExtent(width, height); // from textView class??
bottomLeft = Point(bottom, left);
topRight = Point(bottom + height, left + width);
}
可以看到,函数GetExtent & GetOrigin 被称为TextShape,而包含这些函数的类TextView 是私有继承的。
我的理解是,在私有继承中,所有 parent class 成员都变得不可访问,那么这个 (void TextShape::BoundingBox()) 函数如何尝试访问它?
更新:
感谢大家的回答,我在阅读私有继承时陷入了错误的观念。我觉得,它甚至会阻止访问任何成员,而实际上它会更改访问说明符而不是可访问性。非常感谢您的澄清:)
【问题讨论】:
-
“我的理解是,在私有继承中,所有父类成员都变得不可访问”:如果您无法访问派生类?
标签: c++ design-patterns private-inheritance