开发者

QPointer for abstract base class

开发者 https://www.devze.com 2023-02-25 05:18 出处:网络
I am writing an expression-parsing library. It is written with Qt, a开发者_开发问答nd I have a class structure like this:

I am writing an expression-parsing library. It is written with Qt, a开发者_开发问答nd I have a class structure like this:

QCExpressionNode-Abstract Base Class for all pieces of an expression

QCConstantNode-Constants in an expression (extends QCExpressionNode)

QCVariableNode-Variables in an expression (extends QCExpressionNode)

QCBinaryOperatorNode-Binary Addition, Subtraction, Multiplication, Division and Power operators (extends QCExpressionNode)

I would like to be able to use smart pointers (like QPointer or QSharedPointer), but I am running into the following challenges:

-Can a QPointer be used with abstract classes? If so, please provide examples.

-How to cast a QPointer to a concrete subclass?


I don't see any reason why you can't do this. Take this example:

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"; }
};

Now initialize a QPointer like this:

QPointer<Parent> pointer = new Child();

You can then call methods on the 'abstract' class as you would normally with a QPointer

pointer->AbstractMethod();

Ideally this would be enough, because you could just access everything you need with the abstract methods defined in your parent class.

However, if you really need to differentiate between your child classes or use something that only exists in the child class, you can use 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();
}

I hope that helps.

Extra note: You should also check pointer.isNull() to make sure that the QPointer actually contains something.

0

精彩评论

暂无评论...
验证码 换一张
取 消