私人继承 [英] private inheritance

查看:108
本文介绍了私人继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不明白这一点:

class Base
{
    public:
    Base()
    {
        cout<<"Base" << endl;
    }

    virtual void call()
    {
        cout<<"Base call" << endl; 
    }
};

class Derived: private Base
{
    public:      
    Derived()
    {
        cout<<"Derived" << endl;
    } 
};

int main(void)
{
    Base *bPtr = new Derived(); // This is not allowed
}

是因为有人可能调用call bPtr其实是对派生对象做的?或者有任何其他原因吗?

Is it because someone might call call() using bPtr which is actually done on derived object? Or is there any other reason?

推荐答案

从继承的共同理解,C ++的私人继承是一个可怕的误解:它是不是继承(就类外面的一切而言),但是类的完整实现细节。

From a common understanding of inheritance, C++’ "private inheritance" is a horrible misnomer: it is not inheritance (as far as everything outside of the class is concerned) but a complete implementation detail of the class.

外部,私有继承实际上几乎和组合一样。只有在类的内部,你得到的特殊语法更像是继承而不是组合。

Seen from the outside, private inheritance is actually pretty much the same as composition. Only on the inside of the class do you get special syntax that is more reminiscent of inheritance than composition.

还有一个警告:C ++在句法上将此视为继承,所有这带来的好处和问题,例如范围可见性和辅助功能。此外,C风格的cast(但没有C ++转换!)实际上忽略了可见性,从而成功地将 Derived 指针转换为 Base

There’s a caveat though: C++ syntactically treats this as inheritance, with all the benefits and problems that this entails, such as scope visibility and accessibility. Furthermore, C-style casts (but no C++ cast!) actually ignores visibility and thus succeeds in casting your Derived pointer to Base:

Base* bPtr = (Base*) new Derived();

不用说,这是邪恶

这篇关于私人继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆