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

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


当前回答

简介:

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

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

其他回答

简介:

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

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

如果你公开地从另一个类继承,每个人都知道你在继承,任何人都可以通过基类指针多态地使用你。

如果你继承受保护的只有你的孩子类将能够多态地使用你。

如果你私有继承,只有你自己能够执行父类方法。

这基本上象征着其他类所拥有的关于你与父类关系的知识

class A 
{
    public:
       int x;
    protected:
       int y;
    private:
       int z;
};

class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A    // 'private' is default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};

重要提示:类B, C和D都包含变量x, y和z。这只是访问的问题。

关于受保护继承和私有继承的使用,你可以在这里阅读。

私人:

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

公众:

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

保护:

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


简而言之:

私人:基地

Protected:基础+派生

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

限制继承的可见性将使代码无法看到某些类继承了另一个类:从派生类到基类的隐式转换将不起作用,从基类到派生类的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风格强制转换有意允许以已定义和安全的方式将派生类强制转换为受保护或私有基类,也可以强制转换为其他方向。无论如何都应该避免这种情况,因为它会使代码依赖于实现细节——但如果有必要,您可以使用这种技术。