我正在尝试编写一个非常简单的构造函数init列表,但在一系列对象上却缺乏。编译器说:
parentclass.cpp:5: error: use of deleted function ‘SubClass::SubClass(SubClass&&)’
, subObjects{this}
^
我敢肯定,这是现代C 的一个基本概念,并且看到了许多回答的问题。但是他们都没有澄清我缺少的东西。
这是创建此编译器错误的基本代码(是G 8.3.0(
QTCreator项目文件:
QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES +=
main.cpp
parentclass.cpp
subclass.cpp
HEADERS +=
parentclass.h
subclass.h
main.cpp:
#include <QCoreApplication>
#include "parentclass.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ParentClass pClass;
return a.exec();
}
ParentClass.h:
#ifndef PARENTCLASS_H
#define PARENTCLASS_H
#include <QObject>
#include "subclass.h"
class ParentClass : public QObject
{
Q_OBJECT
public:
explicit ParentClass(QObject *parent = nullptr);
private:
SubClass subObjects[3];
};
#endif // PARENTCLASS_H
ParentClass.cpp:
#include "parentclass.h"
ParentClass::ParentClass(QObject *parent)
: QObject(parent)
, subObjects{ {this} }
{
}
subclass.h:
#ifndef SUBCLASS_H
#define SUBCLASS_H
#include <QObject>
class SubClass : public QObject
{
Q_OBJECT
public:
SubClass(QObject *parent = nullptr);
};
#endif // SUBCLASS_H
subclass.cpp
#include "subclass.h"
SubClass::SubClass(QObject *parent)
: QObject(parent)
{
}
创建动态阵列可能是解决方法,但我正在尝试适应现代C 。由于我主要是一个嵌入式的家伙,因此动态数组也很多毫无疑问。
预先感谢。
编辑注意:我已经更新了一个问题以最低可重复的示例。
另外,如果我将"显式"关键字用于子类的构造函数,这一次会出现这样的错误:
parentclass.cpp:5: error: could not convert ‘(ParentClass*)this’ from ‘ParentClass*’ to ‘SubClass’
, subObjects{this}
^
'显式'关键字可防止构造函数的删除,但是这次编译器不接受指针类型,即使它们都是从同一类派生的。
下一个编辑注:更改了带有双括号的子对象初始列表。
我已经在这个链接中找到了解释,我已经怀疑了。
这是QT开发人员的设计选择。他们出于各种原因使QObject类不可复制,包括不弄乱信号/插槽机制。
为了进行解决方法,我将将子对象定义为子类*指针的数组,然后在ParentClass的构造函数中创建3个实例。
p.s。: Oktalist,这就是为什么您的代码未产生错误的原因。QOBject必须完全定义为QT框架中的。