2013-09-30 131 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?