本文介绍了C ++中的接口继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类结构:

class InterfaceA
{
   virtual void methodA =0;
}

class ClassA : public InterfaceA
{
   void methodA();
}

class InterfaceB : public InterfaceA
{
   virtual void methodB =0;
}

class ClassAB : public ClassA, public InterfaceB
{
   void methodB();
}

现在以下代码无法编译:

Now the following code is not compilable:

int main()
{
    InterfaceB* test = new ClassAB();
    test->methodA();
}

编译器说方法 methodA()是虚拟的,未实现。我认为它是在 ClassA 中实现的(它实现了 InterfaceA )。
有谁知道我的错在哪里?

The compiler says that the method methodA() is virtual and not implemented. I thought that it is implemented in ClassA (which implements the InterfaceA).Does anyone know where my fault is?

推荐答案

那是因为你有两份了InterfaceA 。有关更大的解释,请参阅此处:(你的情况类似于'可怕的钻石')。

That is because you have two copies of InterfaceA. See this for a bigger explanation: https://isocpp.org/wiki/faq/multiple-inheritance (your situation is similar to 'the dreaded diamond').

你需要添加关键字 virtual 从InterfaceA继承ClassA时。从InterfaceA继承InterfaceB时,还需要添加 virtual

You need to add the keyword virtual when you inherit ClassA from InterfaceA. You also need to add virtual when you inherit InterfaceB from InterfaceA.

这篇关于C ++中的接口继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:23
查看更多