C++ Qt 接口或抽象类和 qobject_cast()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3726716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt interfaces or abstract classes and qobject_cast()
提问by Timothy Baldridge
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).
我有一组相当复杂的 C++ 类,它们是从 Java 重写的。所以每个类都有一个继承的类,然后它也实现了一个或多个抽象类(或接口)。
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.
是否可以用于qobject_cast()
从类转换为接口之一?如果我从 派生所有接口QObject
,由于QObject
引用不明确,我会收到错误消息。但是,如果我只有从 继承的基类QObject
,则无法使用,qobject_cast()
因为它与QObject
s 一起操作。
I'd like to be able to throw around classes between plugins and DLLs referred to by their interfaces.
我希望能够在插件和它们的接口引用的 DLL 之间抛出类。
回答by Venemo
After some research and reading the qobject_cast documentation, I found this:
经过一番研究和阅读qobject_cast 文档后,我发现了这一点:
qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.
qobject_cast() 也可以与接口结合使用;有关详细信息,请参阅即插即用示例。
Here is the link to the example: Plug & Paint.
这是示例的链接:Plug & Paint。
After digging up the interfaces headerin the example, I found the Q_DECLARE_INTERFACEmacro that should let you do what you want.
在挖掘示例中的接口标头后,我找到了Q_DECLARE_INTERFACE宏,它应该可以让你做你想做的事。
First, do notinherit QObject
from your interfaces. For every interface you have, use the Q_DECLARE_INTERFACE declaration like this:
首先,不要QObject
从你的接口继承。对于您拥有的每个接口,请使用 Q_DECLARE_INTERFACE 声明,如下所示:
class YourInterface
{
public:
virtual void someAbstractMethod() = 0;
};
Q_DECLARE_INTERFACE(YourInterface, "Timothy.YourInterface/1.0")
Then in your class definition, use the Q_INTERFACESmacro, like this:
然后在您的类定义中,使用Q_INTERFACES宏,如下所示:
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
}