C ++子类,继承和铸造 [英] C++ Subclassing, Inheritance and Casting

查看:89
本文介绍了C ++子类,继承和铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在Qt框架中,有两个类:QTreeWidget和QTreeWidgetitem 。



我已经子类化了一个QTreeWidgetitem:

  
class MyQTreeWidgetitem:public QObject,public QTreeWidgetitem
{

...

public:
int myCustomVariable;
}



我将此添加到QTreeWidget中,执行的操作如下:

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

tree-> addTopLevelItem(item);

现在,如果我需要调用tree-> topLevelItem QTreeWidgetitem *。



然而,我后面是MyQTreeWidgetitem *所以我:

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

这样做的问题是,this-> myCustomVariable不再等于10。



有没有办法保持MyQTreeWidgetitem完好无损?

解决方案

但你可以尝试做一个适当的 dynamic_cast<> ,它将验证对象是否实际上是一个 MyQTreeWidgetItem * 返回0),以及正确执行指针转换(我不知道如果C风格的转换是返回 QObject 的地址。您可以打印出指针,也可以更深入地了解这个问题。


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

In the Qt framework, there are 2 classes: 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.

这篇关于C ++子类,继承和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆