1

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

我希望能够使用智能指针(如QPointeror QSharedPointer),但我遇到了以下挑战: -
可以QPointer与抽象类一起使用吗?如果有,请举例说明。
- 如何将 aQPointer转换为具体的子类?

4

1 回答 1

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

于 2011-04-14T01:49:32.917 回答