gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:59:17 26 4
gpt4 key购买 nike

我有一个公开继承自 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 类的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19092513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com