构造函数 继承qt,派生QT类的复制构造函数

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:

WARNING:: Base class "class QWidget" should be explicitly initialized

in the copy constructor.

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;

};

I got compile error:

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

So, please explain me what I am doing wrong.

解决方案

QObject Class description page tells :

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.

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

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值