Qt多重继承出错 [英] Qt Multiple-inheritance goes wrong
问题描述
我是一个用Qt编写的项目,我有一个QWidget Widget
,应该显示MyTreeWidget
(从QTreeWidget
继承)或MyTableWidget
(从QTableWidget
继承)
I a project of mine, written in Qt, I have a QWidget Widget
that should display either a MyTreeWidget
(inheriting from QTreeWidget
) or a MyTableWidget
(inheriting from QTableWidget
)
-
Widget
不应该知道正在和谁说话.因此,它必须(??)拥有一个My(Tree|Table)Widget
继承的类.
-
MyTreeWidget
和MyTableWidget
共享很多代码,我不想复制粘贴此代码.所以我想让它们从MyGenericView
继承,而MyGenericView
从QAbstractItemView
继承
Widget
shouldn't know who it is talking to. Therefore it must (??) own a class inherited by theMy(Tree|Table)Widget
MyTreeWidget
andMyTableWidget
share a lot of code and I don't want to copy paste this code. So I thought of making them inherit from aMyGenericView
which inherit fromQAbstractItemView
#include <QAbstractItemView>
#include <QTreeWidget>
#include <QTableWidget>
class MyGenericView : public QAbstractItemView
{
Q_OBJECT
public:
MyGenericView();
};
class MyTreeWidget : virtual public QTreeWidget,
virtual public MyGenericView
{
Q_OBJECT
public:
explicit MyTreeWidget(QWidget *parent = 0);
};
class MyTableWidget : public MyGenericView, public QTableWidget { ... };
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0) :
QWidget(parent)
{
m_genericView = new MyTreeWidget();
}
private:
MyGenericView *m_genericView;
};
错误
erreur : invalid new-expression of abstract class type 'MyTableWidget'
m_genericView = new MyTableWidget();
note: because the following virtual functions are pure within 'MyTableWidget':
class MyTableWidget : public QTableWidget, public MyGenericView
与MyTreeWidget相同.
And the same for MyTreeWidget.
那么您将如何纠正呢?
推荐答案
如以下注释中所建议,此答案基于错误的假设.请在下面查看更好的答案.
Edit : As suggested below in comments, this answer is based on faulty assumptions. Please see the better answer below.
首先,您遇到钻石继承问题.您的错误是因为MyTableWidget具有未定义的纯虚拟成员函数.
First, you have an issue of diamond inheritance. Your error is because MyTableWidget has an undefined pure virtual member function.
但是,坦率地说,我不确定为什么您要在这里使用多重继承.如果要节省代码重复,为什么MyTreeWidget和MyTableWidget无法通过组合而不是继承来共享行为元素?这肯定是is-a vs has-a的情况吗?如果它是特定于共享的小部件的代码,但与QTableWidget/QTreeWidget方法没有任何重叠,则只需编写一个将用Tree或Table小部件填充的适配器类即可.
Frankly though, I'm not sure why you want to use multiple inheritance at all here. If it's to save on code duplication, why can't MyTreeWidget and MyTableWidget share behavioural elements via composition instead of inheritence? Is this definitely a case of is-a vs has-a? If it's code specific to widgets that is shared but don't overlap in any way with the QTableWidget/QTreeWidget approach, just write an adaptor class that will be filled with either a Tree or Table widget.
这篇关于Qt多重继承出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!