c++ - 如何在私有(private)继承中调用父成员?

标签 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;
}; 

TextView 类由 TextShape 私有(private)继承,如下所示:

  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);
     }

可以看到,函数 GetExtentGetOrigin 称为 TextShape,而包含这些函数的类 TextView 是私有(private)继承的。

我的理解是,在私有(private)继承中,所有 父类 成员都变得不可访问,那么这个 (void TextShape::BoundingBox()) 函数是如何尝试的访问它?

更新:

谢谢大家的回答,我在看私有(private)继承的时候误入了一个概念。我觉得,它甚至会阻止对任何成员的访问,而实际上它会更改访问说明符而不是可访问性。非常感谢您的澄清:)

最佳答案

在私有(private)继承期间,父类成员变得不可访问其他人,而不是类本身!父类的受​​保护和公共(public)成员仍然可以在派生类中访问类及其 friend 。

例子:

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
}

关于c++ - 如何在私有(private)继承中调用父成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545437/

相关文章:

c++ - Qt - 如何在保留选中状态的同时禁用 QCheckBox?

c++ - 在 VS2008 中编译 boost property_tree 给出 fatal error C1001

java - 如何在2个不同的java-spring项目中设计服务

c++ - 我们可以将 Rcpp 与多个 C++ 函数一起使用吗?

c++ - 如何使用 std::copy() 复制到指向通用字节缓冲区开头的指针的目标?

java - 在基类中使用静态 "member"变量。正在寻找更好的方法。单例?还是工厂?

design-patterns - 为什么不在访问者模式中重载 "visit"方法呢?

c++ - 绑定(bind)到私有(private)继承的成员函数

c++ - 在 C++ 中使用组合进行对象实例化计算

编译器可以删除 C++(虚拟)私有(private)基类吗?