c ++中受保护和私有派生的区别是什么

pas*_*ena 8 c++

可能重复:
C++中private,public和protected继承之间的区别

在c ++中导出为protected或private有什么区别?我无法弄清楚,因为两者似乎都限制了派生类对象的基类成员访问

Dan*_*her 9

让我们考虑一个代码示例,显示使用不同级别的继承允许(或不允许)的内容:

 class BaseClass {};

 void freeStandingFunction(BaseClass* b);

 class DerivedProtected : protected BaseClass
 {
     DerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };
Run Code Online (Sandbox Code Playgroud)

DerivedProtected可以传递给自己,freeStandingFunction因为它知道它来源于BaseClass.

 void freeStandingFunctionUsingDerivedProtected()
 {
     DerivedProtected nonFriendOfProtected;
     freeStandingFunction(&nonFriendOfProtected); // NOT Allowed!
 }
Run Code Online (Sandbox Code Playgroud)

非朋友(类,函数,等等)无法传递DerivedProtectedfreeStandingFunction,因为继承受到保护,因此在派生类之外不可见.私有继承也是如此.

 class DerivedFromDerivedProtected : public DerivedProtected
 {
     DerivedFromDerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };
Run Code Online (Sandbox Code Playgroud)

派生的类DerivedProtected可以告诉它继承自BaseClass,因此可以将自身传递给freeStandingFunction.

 class DerivedPrivate : private BaseClass
 {
      DerivedPrivate()
      {
          freeStandingFunction(this); // Allowed
      }
 };
Run Code Online (Sandbox Code Playgroud)

DerivedPrivate类本身知道它从派生BaseClass,所以本身传递给freeStandingFunction.

class DerivedFromDerivedPrivate : public DerivedPrivate
{
     DerivedFromDerivedPrivate()
     {
          freeStandingFunction(this); // NOT allowed!
     }
};
Run Code Online (Sandbox Code Playgroud)

最后,继承层次结构中的一个非友好类无法看到DerivedPrivate继承BaseClass,因此无法将自身传递给freeStandingFunction.


Lst*_*tor 0

基本上,protected继承比private继承在继承层次结构中向下延伸得更远。有关详细信息,请参阅C++ FAQ Lite