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

How private inheritance allowed me to create object?

本文关键字:允许我 创建对象 继承      更新时间:2023-10-16

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

我私下继承了SealerShield,即使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;
}

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

我正在使用Visual Studio 2012。

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

它不会神奇地返回并使Sealer的构造函数私有,以便Shield无法访问它。 如果子类无法访问基类中的任何内容,私有继承的意义何在? 它完全无能为力。

这并不意味着

相对于Shield Sealer是私有的(Sealer成员从Shield的访问是通过访问类别声明控制的),它只是意味着继承是私有的,这意味着这是不可外部观察的(您可以根据需要操作Shield,但没有实例Shield)。

使用private继承时,无法通过派生类访问基类功能。不能从派生类创建基类指针或引用。

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;
}
相关文章: