c++ - 私有(private)继承如何允许我创建对象?

标签 c++ visual-studio visual-c++ inheritance private

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

我私自继承了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 中保持私有(private);它不能在 Shield 之外或从它派生的类中看到。

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

关于c++ - 私有(private)继承如何允许我创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598406/

相关文章:

c++ - 将字符串添加到文件而不覆盖以前的字符串

c# - Json 列 SQL

xml - 将参数从 Visual Studio 项目模板传递到生成的项目

c++ - OpenGL SuperBible 6 第一个例子报错

c++ - 需要对 C++11 标准中的 8.5.p7 进行一些说明

c++ - 如何将 Git 克隆加载到 QtCreator

visual-studio - Windows Phone 8.1 应用程序签名

c++ - 在 VC++ 项目中开始使用 PCH

c++ - 强制卸载进程的模块

c++ - C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别