如何在私有继承中调用父成员?

时间:2012-03-03 10:42:22

标签: c++ design-patterns private-inheritance

我正在阅读一本关于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;
}; 

此课程TextViewTextShape私下继承,如下所示:

  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())函数如何尝试访问它?

更新

感谢大家的回答,我在阅读有关私人继承时遇到了错误的想法。我觉得,它甚至会阻止访问任何成员,而实际上它会改变访问说明符而不是可访问性。非常感谢你澄清:)

2 个答案:

答案 0 :(得分:3)

在私有继承期间,父成员无法访问其他人的 ,而不是类本身! 父类的受​​保护成员和公共成员仍可在派生中访问上课和朋友。

示例:

class Base
{
    public: int publ;
    protected: int prot;
    private: int priv;
};

class Derived: private Base
{
    friend void g();
    void f()
    {
         priv = 42; //error, priv is private
         prot = 42; //OK
         publ = 42; //OK 
    }
};

int main()
{
    Derived d;
    d.priv = 42; //error
    d.prot = 42; //error
    d.publ = 42; //error
}

void g()
{
    Derived d;
    d.priv = 42; //error
    d.prot = 42; //OK
    d.publ = 42; //OK
}

答案 1 :(得分:3)

以下是继承如何影响访问:

  • 公共继承使公共基础成员公开,受保护成员受到保护,私有基础成员无法访问。

  • 受保护的继承使派生类中的公共和受保护基本成员受到保护,并且私有基本成员不可访问。

  • 私有继承使派生类中的公共和受保护的基本成员成为私有,并且私有基本成员不可访问。