私有继承如何允许我创建对象
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;
}
怎么可能?基类构造函数不应可访问。不是吗?
我正在使用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;
}
相关文章:
- Visual Studio 2017 不允许我创建 C++ 专用模板
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- 我应该只在免费商店上为一次调用创建对象吗?
- 我该如何允许类型的对象非专业化并在不使用指针的情况下识别何时是这种情况
- 是否有一个函数可以显示我创建的类中的对象到 QTextBrowser 中?
- 为什么我的对象似乎被创建了两次
- 为什么GCC不允许我创建"内联静态std::stringstream"?
- 阻止用户创建班级对象的副本,但允许动态的对象有什么好处
- 我如何在参考上使用数据成员而不使用新关键字创建对象
- 为什么在这种情况下不调用我的移动构造函数?(首先分配 r 值引用并创建对象)
- 为什么当我创建 N 个对象的向量时不调用 N 次 CTOR
- 如何在C++中创建一个网格,这将允许我将每个索引设置为一个向量,以便以后操作该向量,然后绘制它
- 我创建的c++istream对象和cin之间的区别在哪里,它在库中的可见位置在哪里
- 私有继承如何允许我创建对象
- C++:我的程序在创建对象时崩溃
- C++当我们创建对象时,构造函数会初始化,但是如果我想再次重新初始化对象,请在 main 的某个时候说该怎么做
- 如何允许程序创建新对象
- 不确定如何使用我的类和命名空间创建对象?c++
- 我在尝试在类中创建对象时面临如何解决链接错误