私有继承如何允许我创建对象?

How private inheritance allowed me to create object?

我有简单的代码,我认为它失败了。

我从 Sealer 私下继承了 Shield,即使 Shield 不是 friend,我仍然能够创建 Shield 的对象.

class Sealer
{
public:

    Sealer()
    {
        cout<<"base constructor;"<<endl;
    }

};

class Shield : private Sealer
{
public:

    void p()
    {
        cout<<"P gets called;"<<endl;
    }
};

int main()                          
{
    Shield d;  //success here
    d.p(); // here too
    return 0;
}

怎么可能? Base class 构造函数不应可访问。不是吗?

我正在使用 Visual Studio 2012。

这并不意味着 Sealer 相对于 Shield 是私有的(Sealer 来自 Shield 的成员访问是通过访问类别声明控制的),它只是意味着继承是私有的,意味着这不是外部可见的(您可以随意操作 Shield 但没有 Shield 实例)。

class Shield : private Sealer 意味着 Sealer 中的所有内容在 Shield 中都是保密的;它不能在 Shield 之外或从它派生的 classes 中看到。

它不会神奇地返回并使 Sealer 的构造函数私有,这样 Shield 就无法访问它。如果子 class 无法访问基 class 的任何内容,私有继承的意义何在?它什么也做不了。

当您使用 private 继承时,您无法通过派生 class 访问基础 class 功能。您不能从派生的 class.

创建基 class 指针或引用
class Sealer
{
   public:

      Sealer() {}
      void p()
      {
         cout<<"P gets called;"<<endl;
      }

};

class Shield : private Sealer
{
};

int main()                          
{
    Shield d;
    d.p();         // Not allowed.
    Sealer& p = d; // Not allowed.
    return 0;
}