问题描述
我了解到,通常,Qt不支持从QObject
派生的类进行多重继承(甚至是 virtual 多重继承).
I understand that in general, multiple inheritance from QObject
-derived classes (even virtual multiple inheritance) is not supported in Qt.
我理解的原因是(我认为)即使在虚拟继承的情况下,Qt类也不自己实际上是从QObject
继承的.例如,如果您尝试从QWidget
和QThread
两者虚拟地派生一个类,则这会将虚拟继承放置在继承链中的不相关位置,而您仍然会遇到两个QObject
实例.
I understand the reason to be (I think) that even in the virtual inheritance case, the Qt classes do not themselves virtually inherit from QObject
. For example, if you attempt to derive a class virtually from both QWidget
and QThread
, this is placing the virtual inheritance in an irrelevant place in the inheritance chain and you still wind up with two QObject
instances.
因此,我认为使用虚拟继承是安全的,并且在Qt中受支持,其中从中派生的唯一Qt类是QObject
本身.
I therefore think it is safe, and supported in Qt, to use virtual inheritance where the ONLY Qt class being derived from is QObject
itself.
我有:
class Top : public QObject {};
class Left : public virtual Top {};
class Right : public virtual Top {};
class Bottom : public Left, public Right {}; // Is this safe, and supported by Qt?
请注意,Bottom
的实例实际上仅具有Top
的一个实例(因此也只有QObject
的一个实例),因此避免在Qt中避免多重继承的原理(甚至是 virtual 多重继承)不适用于此处.
Note that instances of Bottom
truly have only one instance of Top
(and hence only one instance of QObject
), so it seems that the rationale for avoiding multiple inheritance in Qt (even virtual multiple inheritance) does not apply here.
上述构造仍然导致Qt编译器警告Class Bottom inherits from two QObject subclasses Left and Right. This is not supported!
.
The above construct nonetheless results in the Qt compiler warning Class Bottom inherits from two QObject subclasses Left and Right. This is not supported!
.
我正确吗?在这种特定情况下,忽略Qt编译器警告是否安全?上面提到的从QObject直接直接进行虚拟多重继承的结构是否安全并且在Qt中受支持?
Am I correct? Is it safe to ignore the Qt compiler warning in this specific scenario? Is the above construct, involving virtual multiple inheritance directly from QObject, safe and supported in Qt?
推荐答案
否,Qt不以任何方式支持从QObject
的多重继承.
No, multiple inheritance from QObject
is not supported by Qt in any way.
问题不在于虚拟继承,而是Qt的元对象系统.每个QObject
基类都有一个关联的QMetaObject
,它管理信号,时隙,属性等,每个元对象都知道其父级QObject
,例如可以处理父类中存在的信号. Qt moc无法处理来自QObject
或其任何子类的多重继承.
The problem is not with virtual inheritance, it's Qt's meta-object system. Each QObject
base class has an associated QMetaObject
which manages signals, slots, properties, etc, and each meta-object knows its parent QObject
so e.g. signals which exist in parent classes can be handled. The Qt moc is not able to deal with multiple inheritance from QObject
or any of its sub-classes.
这篇关于如果QObject是从DIRECTLY派生的,那么使用* virtual *多重继承是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!