其他分享
首页 > 其他分享> > c – 派生QT类的复制构造函数

c – 派生QT类的复制构造函数

作者:互联网

我有一个公开继承自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

所以,请解释一下我做错了什么.

解决方法:

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对象.

标签:c,qt,copy-constructor
来源: https://codeday.me/bug/20190928/1829311.html