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

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


当前回答

简介:

Private:除了类内部,没有人可以看到它 Protected: Private +派生类可以看到它 公众:全世界都能看到

在继承时,你可以(在某些语言中)在某个方向上改变数据成员的保护类型,例如从protected变为public。

其他回答

Member in base class : Private   Protected   Public   

继承类型:对象继承为:

Private            :   Inaccessible   Private     Private   
Protected          :   Inaccessible   Protected   Protected  
Public             :   Inaccessible   Protected   Public
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…我认为一张小桌子胜过千言万语:)

限制继承的可见性将使代码无法看到某些类继承了另一个类:从派生类到基类的隐式转换将不起作用,从基类到派生类的static_cast也将不起作用。

只有类的成员/友元才能看到私有继承,只有类的成员/友元和派生类才能看到受保护继承。

公共继承

是一种继承。一个按钮就是一个窗口,只要需要一个窗口,就可以传递一个按钮。 类按钮:公共窗口{};

保护继承

implemented-in-terms-of保护。很少有用。在boost::compressed_pair中使用从空类派生并使用空基类优化来节省内存(下面的例子没有使用模板来保持在点上): 结构empty_pair_impl: protected empty_class_1 {non_empty_class_2秒;}; 结构对:private empty_pair_impl { Non_empty_class_2 &second() { 返回这个- >第二; } Empty_class_1 &first() { 返回*;//注意我们返回*this! } };

私有继承

Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here template<typename StorageModel> struct string : private StorageModel { public: void realloc() { // uses inherited function StorageModel::realloc(); } };


公共成员

总 类对{ 公众: 首先第一; 第二第二; }; 访问器 类窗口{ 公众: int getWidth(); };

保护成员

提供对派生类的增强访问 类堆栈{ 保护: 矢量c < >元素; }; 类窗口{ 保护: void registerClass(window_descriptor w); };

私有成员

保持实现细节 类窗口{ 私人: int宽度; };


请注意,c风格强制转换有意允许以已定义和安全的方式将派生类强制转换为受保护或私有基类,也可以强制转换为其他方向。无论如何都应该避免这种情况,因为它会使代码依赖于实现细节——但如果有必要,您可以使用这种技术。

我试着用下面的一张图片来解释继承。

主要的要点是父类的私有成员永远不能从派生类/子类直接访问,但是您可以使用父类的成员函数来访问父类的私有成员。 私有变量始终存在于派生类中,但派生类不能访问它。这就像他们的,但你不能用自己的眼睛看到,但如果你问一个来自父母类的人,然后他可以向你描述。

私人:

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

公众:

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

保护:

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


简而言之:

私人:基地

Protected:基础+派生

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