多重继承冲突
Multiple inheritance conflict
我有以下代码:
class Interface
{
virtual void method()=0;
};
class Base : public Interface
{
virtual void method()
{
//implementation here
}
};
class Parent: public Interface
{
};
class Child : public Base, public Parent
{
};
int main()
{
Child c;//ERROR: cannot instantiate abstract class
}
现在我知道为什么会发生这种情况,因为我继承了 Parent,那么我必须再次实现方法。但它已经在基类中定义,我不想为每个子类覆盖该定义。我认为在 c++ 中有一些标准方法可以摆脱它(告诉编译器它应该使用哪个 Interface 副本)我只是不记得它是什么。
你说的叫做支配。
从链接的文章:
class Parent
{
public:
virtual void function();
};
class Child1 : public virtual Parent
{
public:
void function();
};
class Child2 : public virtual Parent
{
};
class Grandchild : public Child1, public Child2
{
public:
Grandchild()
{
function();
}
};
您有一个菱形层次结构,但不使用虚拟继承。
因此,您最终会在Child
类中获得两个不同的虚拟method()
函数。
修复它的一种方法是转向使用虚拟继承。这样,您只有一个Child::method()
,不需要两个实现。
纯虚函数必须在派生类中定义。如果你不这样做,你的派生类(在本例中为"子级")本身将成为一个无法实例化的抽象类,从而导致错误。
相关文章:
- 关于C++中具有多重继承"this"指针的说明
- C++中模板化异常类的多重继承
- 虚拟继承中是否存在多重继承?
- 如何在 c++ 多重继承中调用父非虚函数?
- 多重继承相同的方法名,没有歧义
- 使用enable_if解决多重继承歧义
- 多重继承导致虚假的模糊虚拟函数过载
- 多重继承和访问不明确的元素
- C++ 多重继承:使用基类 A 的实现实现基类 B 的抽象方法
- 多重继承中的派生类的行为类似于聚合
- 为什么我的 Hippomock 期望在使用多重继承时失败
- 带有此指针的模板类多重继承构造函数不起作用?
- 使用多重继承时出现编译错误
- 增强多重继承的序列化
- 多重继承:跳过'virtual'关键字并拒绝菱形层次结构的使用?
- 仅函数的多重继承 - 没有虚拟和 CRTP
- C++ MSVC 中的访问冲突,但不在 GCC 中进行多重继承和强制转换
- 多重继承冲突
- 我应该如何处理类型而不是方法的多重继承冲突
- 具有冲突方法的多重继承