派生QT类的复制构造函数 [英] copy constructor of derived QT class

查看:389
本文介绍了派生QT类的复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公开继承自 QWidget 的类:

I have a class which is publicly inherited from 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;
};

当我构建项目时,编译器会提示:

When I built my project, compiler complains:


警告::基类QWidget类应该在复制构造函数中显式初始化

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

我从stackoverflow的其他问题检出,并得到我的答案。
但是事实是,当我添加了这样的初始化:

I checked out from other questions on stackoverflow, and got my answer. But the fact is, when I added that initialization like this:

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&)在此上下文中是私有的

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

我做错了。

推荐答案

QObject类说明页面告诉您:


QObject既没有复制构造函数也没有赋值运算符。这是设计。实际上,它们被声明,但在一个私有部分与宏Q_DISABLE_COPY()。事实上,从QObject(直接或间接)派生​​的所有Qt类使用此宏来声明其复制构造函数和赋值运算符为私有。推理是在Qt对象模型页面上关于身份对价值的讨论中找到的。

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是不可复制的设计。

That means you are not supposed to copy QT objects, since QObject is non-copyable by design.

第一个警告告诉你初始化基类(这是QWidget)。如果你想这样做,你将构造一个新的基础对象,我怀疑这是你想做什么。

The first warning tells you to initialize the base class (which is QWidget). If you want to do this, you are going to construct a new base object, and I doubt that is what you want to do.

第二个错误告诉你什么我写在上面:不要复制qt对象。

The second error is telling you what I wrote above : do not copy qt objects.

这篇关于派生QT类的复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆