使用多重继承时的编译错误

编程入门 行业动态 更新时间:2024-10-26 04:29:26
本文介绍了使用多重继承时的编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

无法编译我的程序.由于历史原因,我的应用程序中的类的层次结构有些复杂".现在,我面临另一个问题:由于这种层次结构,它无法编译.我的项目太大,无法在此处显示,但是在下面您可以看到演示问题的示例.有没有简单而优雅的方法来解决它?每个接口/类都有很多方法.预先感谢.

Can't get my program compile. For historical reason I have a bit "complicated" hierarchy of the classes in my application. And now I faced with another problem: it won't compile because of this hierarchy. My project is too big to show it here, but below you can see the example that demonstrates the problem. Is there is a simple and elegant way to fix it? Every interface/class has really big amount of methods. Thanks in advance.

struct ITest { virtual ~ITest() {} virtual void a() = 0; // and many other methods }; struct Test1 : public ITest { virtual ~Test1() {} virtual void a() override {} // and many other methods overrides from ITest // plus a lot of other logic }; struct ExtendedTest1 : public Test1 { virtual ~ExtendedTest1() {} // a lot of some other stuff }; struct ITest2 : public ITest { virtual ~ITest2(){} // and big count of the its methods and logic }; struct MainClass : public ExtendedTest1, public ITest2 { virtual ~MainClass(){} // a lot of logic }; int main() { MainClass mainClassObj; return 0; }

错误:

main.cpp: In function ‘int main()’: main.cpp:36:15: error: cannot declare variable ‘mainClassObj’ to be of abstract type ‘MainClass’ MainClass mainClassObj; ^~~~~~~~~~~~ main.cpp:28:8: note: because the following virtual functions are pure within ‘MainClass’: struct MainClass : public ExtendedTest1, public ITest2 ^~~~~~~~~ main.cpp:4:18: note: virtual void ITest::a() virtual void a() = 0; ^

不要严格判断:)

UPD:在问这个问题之前,我确实尝试过虚拟继承来解决我的问题,但是没有用.因此,在建议重试之后,它就可以了.)因此,替换这些行解决了我的问题:

UPD: before asking this question I really tried virtual inheritance to solve my problem but it didn't work. So after suggestion to try it again, it works) So, replacing these lines solved my problem:

struct Test1 : public ITest ---> struct Test1 : virtual public ITest struct ITest2 : public ITest ---> struct ITest2 : virtual public ITest

我知道,我们必须避免虚拟继承,但是我们不能'由于历史原因和大量的代码

I know, we must avoid virtual inheritance, but we can't 'cause of historical reason and very big amount of code

感谢大家的帮助!

推荐答案

您需要虚拟继承.

虚拟继承可以摆脱多余的功能:

Virtual inheritance can get rid of redundant functions:

相反,如果类B和C实际上从类A继承,则类D的对象将仅包含一组来自类A的成员变量.

Instead, if classes B and C inherit virtually from class A, then objects of class D will contain only one set of the member variables from class A.

如果您虚拟继承,您将摆脱重复的抽象函数.

If you inherit virtually, you will get rid of your duplicate abstract function.

更多推荐

使用多重继承时的编译错误

本文发布于:2023-11-25 17:32:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!