问题描述
我有一个相当复杂的C ++类,从Java重写。所以每个类都有一个继承的类,然后它也实现一个或多个抽象类(或接口)。
I have a fairly complex set of C++ classes that are re-written from Java. So each class has a single inherited class, and then it also implements one or more abstract classes (or interfaces).
可以使用 qobject_cast()
从类转换到其中一个接口?如果我从 QObject
中导出所有接口,由于不明确的 QObject
引用,我得到一个错误。然而,如果我只有基类继承自 QObject
,我不能使用 qobject_cast()
与 QObject
s。
Is it possible to use qobject_cast()
to convert from a class to one of the interfaces? If I derive all interfaces from QObject
, I get an error due to ambiguous QObject
references. If however, I only have the base class inherited from QObject
, I can't use qobject_cast()
because that operates with QObject
s.
我想能够在插件和DLL之间引用
I'd like to be able to throw around classes between plugins and DLLs referred to by their interfaces.
推荐答案
经过一些研究和阅读,我发现:
After some research and reading the qobject_cast documentation, I found this:
这是指向示例的链接:。
Here is the link to the example: Plug & Paint.
挖掘,我发现了宏
首先,不要继承 QObject
从您的接口。对于每个接口,使用Q_DECLARE_INTERFACE声明如下:
First, do not inherit QObject
from your interfaces. For every interface you have, use the Q_DECLARE_INTERFACE declaration like this:
class YourInterface
{
public:
virtual void someAbstractMethod() = 0;
};
Q_DECLARE_INTERFACE(YourInterface, "Timothy.YourInterface/1.0")
在类定义中,使用宏,如下所示:
Then in your class definition, use the Q_INTERFACES macro, like this:
class YourClass: public QObject, public YourInterface, public OtherInterface
{
Q_OBJECT
Q_INTERFACES(YourInterface OtherInterface)
public:
YourClass();
//...
};
经过所有这些麻烦,以下代码工作:
After all this trouble, the following code works:
YourClass *c = new YourClass();
YourInterface *i = qobject_cast<YourInterface*>(c);
if (i != NULL)
{
// Yes, c inherits YourInterface
}
这篇关于Qt接口或抽象类和qobject_cast()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!