c – 受保护的继承是否允许派生类访问其基类的私有成员?

前端之家收集整理的这篇文章主要介绍了c – 受保护的继承是否允许派生类访问其基类的私有成员?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我真的很困惑私人继承和保护继承.

1)在受保护的继承中,public和protected成员成为派生类中的受保护成员.在私人继承中,一切都是私有的.但是,派生类永远不能访问基类的私有成员,是吗?在这两种情况下,派生类都可以访问公共和受保护的成员.是对的吗?

2)我注意到基类的私有成员永远不会被派生类感动.那么为什么私人会员继承?

解决方法

你在第1点是正确的.从基类继承时指定私有,受保护或公开不会在派生类本身上更改任何访问方式.那些访问说明符告诉编译器如何在派生类的实例在其他地方使用基类类成员,或者派生类恰好用作其他类的基类时.

更新:以下可能有助于说明差异:

class Base
{
    private:   int base_pri;
    protected: int base_pro;
    public:    int base_pub;
};

对于派生自base的类:

class With_Private_Base :   private Base   { void memberFn(); };
class With_Protected_Base : protected Base { void memberFn(); };
class With_Public_Base :    public Base    { void memberFn(); };

// this would be the same for all of the above 3 classes:
void With_PXXX_Base::memberFn()
{
    base_pri = 1; // error: `int Base::base_pri' is private
    base_pro = 1; // OK
    base_pub = 1; // OK
}

对于派生自3个派生类的类:

class A : public With_Private_Base { void memberFn(); }
void A::memberFn()
{
    base_pri = 1; // error: `int Base::base_pri' is private
    base_pro = 1; // error: `int Base::base_pro' is protected
    base_pub = 1; // error: `int Base::base_pub' is inaccessible
}

class B : public With_Protected_Base { void memberFn(); }
void B::memberFn()
{
    base_pri = 1; // error: `int Base::base_pri' is private
    base_pro = 1; // OK
    base_pub = 1; // OK
}

class C : public With_Public_Base { void memberFn(); }
void C::memberFn()
{
    base_pri = 1; // error: `int Base::base_pri' is private
    base_pro = 1; // OK
    base_pub = 1; // OK
}

外部访问前三个派生类:

void main()
{
    With_Private_Base   pri_base;
    pri_base.base_pri = 1; // error: `int Base::base_pri' is private
    pri_base.base_pro = 1; // error: `int Base::base_pro' is protected
    pri_base.base_pub = 1; // error: `int Base::base_pub' is inaccessible

    With_Protected_Base pro_base;
    pro_base.base_pri = 1; // error: `int Base::base_pri' is private
    pro_base.base_pro = 1; // error: `int Base::base_pro' is protected
    pro_base.base_pub = 1; // error: `int Base::base_pub' is inaccessible

    With_Public_Base    pub_base;
    pub_base.base_pri = 1; // error: `int Base::base_pri' is private
    pub_base.base_pro = 1; // error: `int Base::base_pro' is protected
    pub_base.base_pub = 1; // OK
}
原文链接:https://www.f2er.com/c/113070.html

猜你在找的C&C++相关文章