2013-09-30 268 views
8

我有一個是公開從QWidget繼承的類:拷貝構造函數

class MyWidget : public QWidget 
{ 
    Q_OBJECT 
public: 
    MyWidget(const MyWidget& other) 
     : 
    obj1(other.obj1), 
    obj2(other.obj2) 

private: 
    some_class obj1; 
    some_class obj2; 
}; 

當我建我的項目,編譯器抱怨:

WARNING:: Base class "class QWidget" should be explicitly initialized in the copy constructor.

我從其他的問題檢查出來stackoverflow,並得到了我的答案。 但事實是,當我添加了初始化像這樣:

class MyWidget : public QWidget 
{ 
    Q_OBJECT 
public: 
    MyWidget(const MyWidget& other) 
     : 
    QWidget(other), //I added the missing initialization of Base class 
    obj1(other.obj1), 
    obj2(other.obj2) 

private: 
    some_class obj1; 
    some_class obj2; 
}; 

我得到了編譯錯誤:

QWidget::QWidget(const QWidget&) is private within this context

所以,請給我解釋一下我在做什麼錯。

+5

似乎'QWidget'沒有設計成拷貝構造,這意味着你的派生類型不應該是。 – juanchopanza

+0

你是否明確地爲'QWidget'創建了一個拷貝構造函數,或者你把它留給了編譯器? – Olayinka

+0

我不需要爲QWidget創建一個Copy-Constructor。我可以在我的對象的拷貝構造函數的init列表中初始化調用QWidget :: Cpoy-Constructor的對象。 –

回答

16

QObject Class描述頁面告訴:

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.

這意味着你不應該複製QT對象,因爲QObject的是設計不可複製的。

第一個警告告訴你初始化基類(它是QWidget)。如果你想這樣做,你將要構建一個新的基礎對象,我懷疑這是你想要做什麼。

第二個錯誤是告訴你我上面寫的是什麼:不要複製qt對象。

9

所有Qt類都是從QObject派生的不可複製的。

在C++中,禁止像在多態對象上進行復制那樣的特定值語義操作是很常見的做法。 Qt的給出瞭如果副本允許的QObject在其documentation的話會產生問題的例子:

A Qt Object...

  • might have a unique QObject::objectName(). If we copy a Qt Object, what name should we give the copy?
  • has a location in an object hierarchy. If we copy a Qt Object, where should the copy be located?
  • can be connected to other Qt Objects to emit signals to them or to receive signals emitted by them. If we copy a Qt Object, how should we transfer these connections to the copy?
  • can have new properties added to it at runtime that are not declared in the C++ class. If we copy a Qt Object, should the copy include the properties that were added to the original?