今天给一些代码老外review,老外指出我写的dynamic_cast<QTXXXXX*>(pObject)的问题,告诉我要用qobject_cast。
查了下Qt的Assitant关于qobject_cast的介绍:
T qobject_cast ( QObject * object )
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.
The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.
A class is considered to inherit itself.
Example:
QObject *obj = new QTimer; // QTimer inherits QObject
QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj
QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == 0
The qobject_cast() function behaves similarly to the standard C++ dynamic_cast() , with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.
qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.
Warning: If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.
主要就是对于继承自Q_OBJECT的类使用,不需要RTTI支持。
在Qt编程中,老外建议使用qobject_cast而非dynamic_cast进行类型转换。qobject_cast适用于继承自QObject的类,并且不需要RTTI支持。当转换的对象为0或不匹配时,它会返回0。qobject_cast的行为类似于C++的dynamic_cast,但不受动态库边界限制,并且可以配合接口使用。

1309

被折叠的 条评论
为什么被折叠?



