'QObject& QObject::operator=(const QObject&)' is private——無法將自訂的QObject子類放入Qt容器(container)中

來源:互聯網
上載者:User

標籤:use   store   官方   amp   建構函式   and   this   other   ack   

先貼出問題的代碼:

 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;

 



'QObject& QObject::operator=(const QObject&)' is private——無法將自訂的QObject子類放入Qt容器(container)中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.