我看不出有什么理由不能做到这一点。就拿这个例子:
class Parent : public QObject
{
public:
virtual void AbstractMethod() = 0;
};
class Child: public Parent
{
public:
virtual void AbstractMethod() { }
QString PrintMessage() { return "This is really the Child Class"; }
};
现在初始化像这样的QPointer:
QPointer<Parent> pointer = new Child();
然后,您可以调用的 '抽象' 类方法,你用QPointer
pointer->AbstractMethod();
通常会理想情况下,这足够了,因为您可以使用父类中定义的抽象方法访问所需的所有内容。
但是,如果您确实需要区分您的子类或使用仅存在于子类中的某些内容,则可以使用dynamic_cast。
Child *_ChildInstance = dynamic_cast<Child *>(pointer.data());
// If _ChildInstance is NULL then pointer does not contain a Child
// but something else that inherits from Parent
if (_ChildInstance != NULL)
{
// Call stuff in your child class
_ChildInstance->PrintMessage();
}
我希望有帮助。
特别提示:您还应该检查pointer.isNull()以确保QPointer实际上包含某些内容。
来源
2011-04-14 01:49:32
Liz
我可以使用'qobject_cast'吗?而且,我可以使用typedef,比如'QCExpressionNode_ptr'作为'QPointer'吗? –
2011-04-14 02:04:30
@Nathan Moos文档qobject_cast说:“qobject_cast()函数的行为与标准C++ dynamic_cast()”类似,所以我认为应该可以。我也尝试添加typedef QPointer Parentptr;并使用它而不是每次都声明它,并且它工作。所以,你也可以这样做。 –
Liz
2011-04-14 15:56:50
谢谢!这完全回答了我的问题。 – 2011-04-16 00:00:57