【发布时间】:2025-12-08 15:15:02
【问题描述】:
无法编译我的程序。由于历史原因,我的应用程序中的类层次结构有点“复杂”。现在我面临另一个问题:由于这种层次结构,它不会编译。我的项目太大,无法在此处显示,但您可以在下面看到演示问题的示例。有没有一种简单而优雅的方法来解决它?每个接口/类都有大量的方法。 提前致谢。
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:在问这个问题之前,我确实尝试过虚拟继承来解决我的问题,但没有奏效。所以在建议再试一次之后,它可以工作)所以,替换这些行解决了我的问题:
struct Test1 : public ITest ---> struct Test1 : virtual public ITest
struct ITest2 : public ITest ---> struct ITest2 : virtual public ITest
我知道,我们必须避免虚拟继承,但我们不能因为历史原因和非常多的代码
感谢大家的帮助!
【问题讨论】:
-
也许你需要virtual iheritance?
-
@Chipster,你能改写你的评论来回答吗?我想将其标记为“答案”。确实,虚拟继承解决了我的问题。我真的试过了,但我做错了。呼吸了几分钟的新鲜空气后,我做到了:)
-
我写了它作为你的答案。
标签: c++ inheritance compiler-errors multiple-inheritance