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

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


当前回答

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

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

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

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

其他回答

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

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

它来自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
}

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

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

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

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:基础+派生

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