开发者

Polymorphic QSharedPointer

开发者 https://www.devze.com 2023-01-12 08:57 出处:网络
I\'m trying to use QSharedPointer in my polymorphic stucture, but I couldn\'t find right syntax to convert pointer of base class to pointer of derived class.

I'm trying to use QSharedPointer in my polymorphic stucture, but I couldn't find right syntax to convert pointer of base class to pointer of derived class.

struct Switch : State {
 int a;
};

QSharedPointer <State> myState=QSharedPointer <State开发者_JAVA百科>(new Switch);  

QSharedPointer <Switch> mySwitchTest= ??? myState;

What should I put in the place of ???


Use qSharedPointerCast():

QSharedPointer <Switch> mySwitchTest= qSharedPointerCast<Switch>(myState);

Or call staticCast() on the smart pointer:

QSharedPointer <Switch> mySwitchTest= myState.staticCast<Switch>();

Both versions are basically equivalent to doing static_cast on raw pointers.


For a dynamic cast, use qSharedPointerDynamicCast:

class Derived : public Base { ... };
QSharedPointer<Base> base...

QSharedPointer<Derived> derived = qSharedPointerDynamicCast<Derived>( base );

There are also equivalents for static_cast (as in silico showed), qobject_cast and const_cast. Pick your poison.

0

精彩评论

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