如何使用私有继承的方法覆盖纯虚方法?

Dan*_*tor 2 c++ inheritance multiple-inheritance pure-virtual private-inheritance

我有以下内容:

class Abstract
{
    virtual void AbstractMethod() = 0;
};

class Implementer
{
    void AbstractMethod() {};
};

class Concrete : public Abstract, private Implementer
{};
Run Code Online (Sandbox Code Playgroud)

我无法实例化,Concrete因为AbstractMethod不会覆盖纯虚方法.我究竟做错了什么?

M2t*_*2tM 6

您在这里使用多重继承.

Concrete有两个分别处理的层次结构:

摘要与实施者.由于Abstract与实现者没有关系,因此在这种情况下使用virtual(对于兄弟继承)将失败.

您需要覆盖派生类中的虚函数.你不能以你尝试的方式做到这一点.

具体来说,如果您要重新编写它,它将起作用:

class Abstract
{
    virtual void AbstractMethod() = 0;
};

class Implementer : private Abstract
{
    void AbstractMethod() {};
};

class Concrete : public Implementer
{};
Run Code Online (Sandbox Code Playgroud)

我想指出你在Concrete中使用公共或私有继承不会影响问题.如果您在原始示例中将Implementer更改为public,则它仍然不能成为具体类.

有用的辅助信息:尽可能避免多重继承,有利于组合而不是继承,并且更喜欢浅层继承.http://en.wikipedia.org/wiki/Composition_over_inheritance

如果您要经历多重继承的路由,请注意C++中默认的单独继承层次结构,并且需要虚拟继承来组合不同的路径(虚拟方法仍然需要派生类来覆盖它们,而不是兄弟类):http://en.wikipedia.org/wiki/Multiple_inheritance