我正在编写一个表达式解析库。它是用Qt编写的,我有一个这样的类结构:
表达式所有部分的QCExpressionNode-Abstract基类
表达式中的QCConstantNode-Constants (扩展QCExpressionNode)
表达式中的QCVariableNode-Variables (扩展QCExpressionNode)
QCBinaryOperatorNode-Binary加法、减法、乘法、除法和幂运算符(扩展QCExpressionNode)
我希望能够使用智能指针(如QPointer或QSharedPointer),但我遇到了以下挑战:
-Can a QPointer可以与抽象类一起使用?如果有,请举例说明。
将QPointer转换为具体的子类的-How?
发布于 2011-04-14 09:49:33
我看不出你有什么理由不能这么做。举个例子:
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确实包含某些内容。
https://stackoverflow.com/questions/5657269
复制相似问题