2011-04-14 104 views
0

我在写一个表达式解析库。 这是写使用Qt,和我有一个类结构是这样的:
QCConstantNode -Constants在表达
QCExpressionNode - 抽象基类的表达式的所有条(延伸QCExpressionNode
QCVariableNode - 变量在表达式(扩展QCExpressionNode
QCBinaryOperatorNode - 二进制加法,减法,乘法,除法和电力运营商(延伸QCExpressionNode抽象基类QPointer

我希望能够使用智能指针(如QPointerQSharedPointer),但我我遇到以下挑战:
可以使用抽象类来使用QPointer吗?如果是这样,请举例说明。
- 如何将QPointer投射到一个具体的子类?

回答

3

我看不出有什么理由不能做到这一点。就拿这个例子:

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实际上包含某些内容。

+0

我可以使用'qobject_cast'吗?而且,我可以使用typedef,比如'QCExpressionNode_ptr'作为'QPointer '吗? – 2011-04-14 02:04:30

+1

@Nathan Moos文档qobject_cast说:“qobject_cast()函数的行为与标准C++ dynamic_cast()”类似,所以我认为应该可以。我也尝试添加typedef QPointer Parentptr;并使用它而不是每次都声明它,并且它工作。所以,你也可以这样做。 – Liz 2011-04-14 15:56:50

+0

谢谢!这完全回答了我的问题。 – 2011-04-16 00:00:57