开发者

C++ Subclassing, Inheritance and Casting

开发者 https://www.devze.com 2023-02-09 16:31 出处:网络
This specific conundrum is hard for me to explain so I\'ll try as best I can. In the Qt framework, there are 2 开发者_StackOverflowclasses: QTreeWidget and QTreeWidgetitem.

This specific conundrum is hard for me to explain so I'll try as best I can.

In the Qt framework, there are 2 开发者_StackOverflowclasses: QTreeWidget and QTreeWidgetitem.

I have subclassed a QTreeWidgetitem:


class MyQTreeWidgetitem : public QObject, public QTreeWidgetitem
{

...

public:
  int myCustomVariable;
}

I add this to a QTreeWidget doing something like:


MyQTreeWidgetitem *item = new MyQTreeWidgetitem;
item->myCustomVariable = 10;

tree->addTopLevelItem(item);

Now, if ever I need to call tree->topLevelItem(x), all I get back is the QTreeWidgetitem*.

However, what I'm after is the MyQTreeWidgetitem* so I:


MyQTreeWidgetItem *theitem = (MyQTreeWidgetItem*)tree->topLevelItem(n);

The problem with this is that theitem->myCustomVariable no longer equals 10.

Is there a way to keep MyQTreeWidgetitem intact?


I don't know Qq, but you could try doing a proper dynamic_cast<> which will verify whether the object is actually a MyQTreeWidgetItem* (otherwise returns 0), as well as performing the pointer conversion properly (I'm not sure if the C-style cast is returning the address of the QObject). You can print out the pointers and get more insight into this problem too.


Using a C-style cast in a C++ program is usually a bad idea. It may be okay to use it for primitive types, but should be avoided for classes. Although in this particular case it may be fine, one day you'll find yourself in deep trouble because of it.

Using dynamic_cast<> is probably fine. As you don't use virtual inheritance, you may wish to use static_cast<> too, it has advantage of not requiring RTTI (some platforms may have poor support of it) and being slightly faster. I also heard that dynamic_cast sometimes doesn't work properly across shared library boundaries.

For downcasting between QObject subclasses there is also qobject_cast<> available in Qt. It won't help you in this case as QTreeWidgetItem isn't a QObject subclass, but may help you elsewhere where you need to cast from QObject* to MyQTreeWidgetItem*. It is also used to cast to interfaces if you use Qt plugins mechanism.

0

精彩评论

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