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

时间:2011-05-05 21:42:43

标签: c++

  

可能重复:
  Difference between private, public and protected inheritance in C++

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

5 个答案:

答案 0 :(得分:9)

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

 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

答案 1 :(得分:3)

使用此矩阵(取自here)来决定继承成员的可见性:

inheritance\member  |     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

答案 2 :(得分:1)

private只允许声明它的类访问它 protected允许该类和派生/子类像私有

一样进行访问

答案 3 :(得分:1)

我添加了关于Inheritance&的非常详细的解释。 this Q中的Access Specifiers。它解释了所有类型的继承以及访问说明符如何与它们一起使用。看看。
Hth :)

答案 4 :(得分:0)

基本上,protected继承继承了继承层次结构,而不是private继承。有关详细信息,请参阅the C++ FAQ Lite