我正在编写一个表达式解析库。
它是用Qt写的,我有这样一个类结构:
QCExpressionNode
-表达式所有部分的抽象基类
QCConstantNode
-表达式中的常量(扩展QCExpressionNode
)
QCVariableNode
-表达式中的变量(扩展QCExpressionNode
)
QCBinaryOperatorNode
-二进制加法、减法、乘法、除法和幂运算符(扩展QCExpressionNode
)
我希望能够使用智能指针(如 QPointer
或 QSharedPointer
),但我遇到了以下挑战:
- QPointer
可以与抽象类一起使用吗?如果是,请提供示例。
- 如何将 QPointer
转换为具体的子类?
最佳答案
我看不出有任何你不能这样做的理由。举个例子:
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 实际上包含某些内容。
关于c++ - 抽象基类的 QPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657269/