c ++中的protected和private派生之间有什么区别?

可能重复:
C ++中私有,公共和受保护继承之间的区别

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


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

 class BaseClass {};

 void freeStandingFunction(BaseClass* b);

 class DerivedProtected : protected BaseClass
 {
     DerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };

DerivedProtected可以将自身传递给freeStandingFunction因为它知道它来自BaseClass

 void freeStandingFunctionUsingDerivedProtected()
 {
     DerivedProtected nonFriendOfProtected;
     freeStandingFunction(&nonFriendOfProtected); // NOT Allowed!
 }

非朋友(类,函数,任何)无法将DerivedProtected传递给freeStandingFunction ,因为继承是受保护的,因此在派生类之外不可见。 私人继承也是如此。

 class DerivedFromDerivedProtected : public DerivedProtected
 {
     DerivedFromDerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };

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

 class DerivedPrivate : private BaseClass
 {
      DerivedPrivate()
      {
          freeStandingFunction(this); // Allowed
      }
 };

DerivedPrivate类本身知道它从BaseClass派生,所以可以将它自己传递给freeStandingFunction

class DerivedFromDerivedPrivate : public DerivedPrivate
{
     DerivedFromDerivedPrivate()
     {
          freeStandingFunction(this); // NOT allowed!
     }
};

最后,继承层次下面的非友元类无法看到DerivedPrivate继承自BaseClass ,因此无法将其自身传递给freeStandingFunction


使用这个矩阵(取自这里)决定继承成员的可见性:

inheritancemember  |     private     |   protected   |   public
--------------------+-----------------+---------------+--------------
private             |  inaccessible   |    private    |  private
protected           |  inaccessible   |    protected  |  protected
public              |  inaccessible   |    protected  |  public
--------------------+-----------------+---------------+--------------

例1:

class A { protected: int a; }
class B : private A {};       // 'a' is private inside B

例2:

class A { public: int a; }
class B : protected A {};     // 'a' is protected inside B

例3:

class A { private: int a; }
class B : public A {};        // 'a' is inaccessible outside of A

private只允许声明的类访问它protected允许类和派生/子类访问,就像它是私有的一样

链接地址: http://www.djcxy.com/p/78547.html

上一篇: What is difference between protected and private derivation in c++

下一篇: Is partial class template specialization the answer to this design problem?