【问题标题】:Copy constructor doesnt happen when assign a QGraphicsDropShadowEffect object in qt在 qt 中分配 QGraphicsDropShadowEffect 对象时不会发生复制构造函数
【发布时间】:2020-10-18 11:52:11
【问题描述】:

我声明了两个QGraphicsDropShadowEffect 空指针,因为在qt 中对一些QPushButton(s) 添加了阴影效果:

QGraphicsDropShadowEffect *effectButton1;
QGraphicsDropShadowEffect *effectButton2;

然后我将内存分配给effectButton1,并调用setXOffset、setYOffset、setBlurRadius 方法为effectButton1 对象设置阴影选项。

effectButton1 = new QGraphicsDropShadowEffect();
effectButton1->setXOffset(3);
effectButton1->setYOffset(3);
effectButton1->setBlurRadius(7);

现在,我想在使用 new 运算符创建实例时将 effectButton1 对象分配给 effectButton2。如您所知,在以下语句中,必须发生复制构造函数,并且我使用setXOffset(3) 设置的值也必须设置为effectButton2 内存。但是两个对象的 xOffset() 的返回值不同(effectButton1 是 3 和 effectButton2 是 8):

effectButton2 = new QGraphicsDropShadowEffect(effectButton1);
QMessageBox::information(this, "", QString("%1").arg(effectButton1->xOffset()));
QMessageBox::information(this, "", QString("%1").arg(effectButton2->xOffset()));

我预计,当我调用effectButton1->setXOffset(3) 并将effectButton1 分配给effectButton2 时,将为effectButton2 内存设置相同的XOffset 值,因为必须发生复制构造函数。

【问题讨论】:

  • 您实际上是在创建一个新的QGraphicsDropShadowEffect,并将effectButton1 作为其父对象。 QGraphicsDropShadowEffect 没有复制构造函数。
  • @G.M.请准确地解释我。我听不懂。
  • 离题:俄语中的“Battle-tested”是“закалённый в бою”。 “битва проверено”在语法上不正确,只是两个单词的连接,没有任何意义。
  • @WiktorStribiżew 非常感谢。我会纠正它...

标签: c++ qt copy-constructor


【解决方案1】:

考虑一下声明...

effectButton2 = new QGraphicsDropShadowEffect(effectButton1);

这将调用this constructor...

QGraphicsDropShadowEffect(QObject *parent)

使用effectButton1 作为parent 参数。正如您似乎认为的那样,它不会调用复制构造函数。实际上QGraphicsDropShadowEffect 没有复制构造函数,因为它继承自不可复制的QObject。

如果您想在effectButton2 中复制effectButton1 的状态,您需要手动复制相应的属性,例如...

effectButton2 = new QGraphicsDropShadowEffect;
effectButton2->setXOffset(effectButton1->xOffset());

等等

【讨论】:

  • 不是说实现类的时候会自动实现сopy-constructor特性吗?
  • 不,没有没有复制构造函数。
  • 如果我们想要一个复制构造函数,我们必须像这样实现例如:Class(const Class &c) 不是吗?我说的对吗?
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2018-10-07
  • 2015-12-05
  • 2020-01-11
相关资源
最近更新 更多