我有以下内容:
class Abstract
{
virtual void AbstractMethod() = 0;
};
class Implementer
{
void AbstractMethod() {};
};
class Concrete : public Abstract, private Implementer
{};
我无法实例化Concrete
,因为纯虚方法AbstractMethod
未被覆盖。我究竟做错了什么?
我有以下内容:
class Abstract
{
virtual void AbstractMethod() = 0;
};
class Implementer
{
void AbstractMethod() {};
};
class Concrete : public Abstract, private Implementer
{};
我无法实例化Concrete
,因为纯虚方法AbstractMethod
未被覆盖。我究竟做错了什么?
您在这里使用多重继承。
具体有两个层次分别处理:
抽象和实施者。由于 Abstract 与 Implementer 没有关系,因此在这种情况下(用于兄弟继承)您对 virtual 的使用将失败。
您需要覆盖派生类中的虚函数。你不能以你尝试的方式去做。
具体来说,如果您要这样重写它,它将起作用:
class Abstract
{
virtual void AbstractMethod() = 0;
};
class Implementer : private Abstract
{
void AbstractMethod() {};
};
class Concrete : public Implementer
{};
我想指出您在 Concrete 中使用公共或私有继承不会影响问题。如果您在原始示例中将 Implementer 更改为 public,它仍然无法成为具体类。
有用的辅助信息:尽可能避免多重继承,支持组合而不是继承,并且更喜欢浅继承而不是深继承。http://en.wikipedia.org/wiki/Composition_over_inheritance
如果您正在经历多重继承的路线,请注意 C++ 中默认的单独继承层次结构,并且需要虚拟继承来组合不同的路径(虚拟方法仍然需要派生类来覆盖它们,而不是兄弟类):http://en.wikipedia.org/wiki/Multiple_inheritance