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

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


当前回答

简介:

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

在继承时,你可以(在某些语言中)在某个方向上改变数据成员的保护类型,例如从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…我认为一张小桌子胜过千言万语:)

1)公共继承:

a.基类的私有成员在派生类中不可访问。

b.基类的受保护成员在派生类中仍然受保护。

c.基类的公共成员在派生类中保持为公共。

因此,其他类可以通过派生类对象使用基类的公共成员。

2)受保护遗产:

a.基类的私有成员在派生类中不可访问。

b.基类的受保护成员在派生类中仍然受保护。

c.基类的公共成员也成为派生类的受保护成员。

因此,其他类不能通过派生类对象使用基类的公共成员;但它们可用于派生的子类。

3)私人继承:

a.基类的私有成员在派生类中不可访问。

b.基类的Protected & public成员变成派生类的private成员。

因此,基类的成员不能被其他类通过派生类对象访问,因为它们在派生类中是私有的。甚至是Derived的子类 类不能访问它们。

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

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

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

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

我发现了一个简单的答案,所以我想把它贴出来,作为我未来的参考。

它来自http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/的链接

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};

class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:

        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};

int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}

私人:

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

公众:

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

保护:

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


简而言之:

私人:基地

Protected:基础+派生

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