添加到 QList 的对象会丢失所有成员数据
我正在制作一个名为 ControlIcon 的自定义类的 QList。我创建 ControlIcons,并使用成员变量加载它们,然后将它们添加到列表中。这是附加代码:
this->cueList.append(firstOne);
这是 QList 的声明:
QList<控制图标 *>提示列表;
如果我在追加后立即中断,我可以看到刚刚添加的 ControlIcon 充满了成员,并且看起来很好。我查看列表,发现已附加的 ControlIcon(它确实附加了 ControlIcon)根本没有成员。我之前制作过自定义对象的 QList,所以我很困惑。有人可以帮忙吗?
I'm making a QList of a custom class called ControlIcon. I create the ControlIcons, and load them up with member variables, and then add them to the list. Here's the append code:
this->cueList.append(firstOne);
Here's the declaration of the QList:
QList< ControlIcon *> cueList;
If I break right after the append, I can see that the ControlIcon that was just added is full of members, and appears fine. I look in the list, and the ControlIcon that's been appended (and it does append a ControlIcon) has no members at all. I've made a QList of custom objects before, so I'm very confused. Could someone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的自定义类必须是可分配,这意味着它必须提供默认构造函数、复制构造函数和赋值运算符。如果他们不这样做,就会发生像这样奇怪的事情。
Your custom class must be assignable, that means it must provide a default constructor, a copy constructor and a assignment operator. If they don't, weird things like this can happen.
cueList
包含指向ControlIcon
对象的指针,但它不负责创建或保留这些ControlIcon
对象。你是如何获得指针firstOne
的?如果它指向堆栈上的某个对象,那么当您稍后尝试使用它时,该对象将无效。如果它是使用new
创建的,它将保持有效,直到您使用delete
清理它。cueList
contains pointers toControlIcon
objects, but it is not responsible for creating or keeping thoseControlIcon
objects. How did you get the pointerfirstOne
? If it points to something on the stack, that object would be invalid when you try to use it later. If it was created withnew
, it will stay valid until you clean it up usingdelete
.我将列表的数据类型更改为 SerialController (ControlIcon 的子级),这就是我试图添加到其中的内容,并且它工作正常。这真的很烦人,因为还有其他类型的控制器,但我想它现在必须工作。
I changed the data type of the list to be SerialController (the child of ControlIcon), which is what I was trying to add to it, and it works fine. This is really annoying, because there's other types of controllers, but I guess it will have to work for now.