'QObject& QObject::operator=(const QObject&)' is private——无法将自定义的QObject子类放入Qt容器(container)中...

先贴出问题的代码:

 1 #include<QCoreApplication>
 2 classMyObject:publicQObject
 3 {
 4 public:
 5 MyObject(QObject*parent =0):
 6 QObject(parent)
 7 {
 8 }
 9 private:
10 int m_id;
11 };
12 int main(int argc,char*argv[])
13 {
14 QCoreApplication a(argc, argv);
15 QList<MyObject>list;
16 list<<MyObject(0);
17 return a.exec();
18 }

 

 
编译后有以下错误,非常多:
 
总结一下问题:
MyObject是继承于QObject的子类,当将其的实例放入Qt的容器中(如QList、QHash等),就会报以上错误。
关于原因,官方文档里有以下说明:

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

 

简单说就是:

QObject的拷贝构造函数是私有的,当把其子类放入容器时无法完成构造其副本。

解决方法就是,使用指针。将自定义的子类以指针的形式保存在容器中。

 

QList<MyObject *>list;

 



转载于:https://www.cnblogs.com/foundkey/p/6021709.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值