无法编译我的程序.由于历史原因,我的应用程序中的类的层次结构有些复杂".现在,我面临另一个问题:由于这种层次结构,它无法编译.我的项目太大,无法在此处显示,但是在下面您可以看到演示问题的示例.有没有简单而优雅的方法来解决它?每个接口/类都有很多方法.预先感谢.
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.
更多推荐
使用多重继承时的编译错误
发布评论