我看不出有什么理由你不能这样做。举个例子:
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 实际上包含某些内容。