c++中公共继承、私有继承和受保护继承之间的区别是什么?

我在SO上找到的所有问题都是针对具体案例的。


当前回答

它与基类的公共成员如何从派生类中公开有关。

Public——>基类的Public成员为Public(通常为默认值) Protected ->基类的公共成员将受到保护 Private ->基类的public成员为Private

As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.

其他回答

它本质上是派生类中基类的公共和受保护成员的访问保护。通过公共继承,派生类可以看到基类的公共成员和受保护成员。而私有继承则不能。使用protected,派生类及其派生的任何类都可以看到它们。

私人:

基类的私有成员只能被该基类的成员访问。

公众:

基类的公共成员可以被该基类的成员、其派生类的成员以及基类和派生类之外的成员访问。

保护:

基类的成员可以访问基类的受保护成员,也可以访问其派生类的成员。


简而言之:

私人:基地

Protected:基础+派生

Public: base + derived +任何其他成员

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

基于这个例子的java…我认为一张小桌子胜过千言万语:)

它与基类的公共成员如何从派生类中公开有关。

Public——>基类的Public成员为Public(通常为默认值) Protected ->基类的公共成员将受到保护 Private ->基类的public成员为Private

As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.

公共继承对IS-A关系建模。与

class B {};
class D : public B {};

每个D都是B。

私有继承为IS-IMPLEMENTED-USING关系建模(或者其他什么关系)。与

class B {};
class D : private B {};

D不是B,但每个D都在实现过程中使用了B。私有继承总是可以通过使用包含来消除:

class B {};
class D {
  private: 
    B b_;
};

这个D也可以用B实现,在这种情况下使用它的b_。与继承相比,包含在类型之间的耦合不那么紧密,因此通常应该首选它。有时使用容器代替私有继承不像私有继承那样方便。这通常是懒惰的蹩脚借口。

我想没有人知道什么是受保护的继承模型。至少我还没看到任何令人信服的解释。