在QMap中插入QObject * -不能初始化或传递指针
Inserting QObject * in QMap - cannot initialize or pass the pointer
我设置了两个类,InputFile
和InputStream
。两者都继承QObject
,并使用Q_OBJECT
宏初始化。
InputFile
包含一个QMap<int,InputStream*>
,创建InputStream
对象并将它们插入QMap
。
InputStream
用显式构造函数初始化,然后像这样插入到映射中:
InputStream myStream = InputStream(this, *myParameter);
_myMap.insert(myInt, *myStream);
编译器在引用插入调用时返回一些错误:
/opt/Qt5.5.0/5.5/gcc/include/QtCore/qobject.h:461: error: 'QObject::QObject(const QObject&)' is private
Q_DISABLE_COPY(QObject)
^
/home/myusername/Documents/Projects/MyProject/inputfile.cpp:17: error: no match for 'operator*' (operand type is 'InputStream')
_myMap.insert(myInt, *myStream);
^
然后尝试将InputStream
初始化为指针:
InputStream *myStream = InputStream(this, *myParameter);
在这种情况下,编译器返回以下错误:
/home/myusername/Documents/Projects/MyProject/inputfile.cpp:16: error: cannot convert 'InputStream' to 'InputStream*' in initialization
InputStream *myStream = InputStream(this, *myParameter);
^
我也尝试在插入调用中使用引用(&
),但这仍然返回第一个错误。
如何根据需要初始化对象并将其插入QMap
中?
第一个错误意味着你不能复制QObject子类,所以你应该使用指针指向它(正如你在开始时说的),所以你需要第二种方法,但是你忘记了分配内存和构造对象(你忘记了new关键字)。所以使用:
InputStream *stream = new InputStream(...);
如果_myMap
确实是QMap<int,InputStream*>
,那么您应该只插入原始指针,而不是指针指向的对象:
_myMap.insert(myInt, myStream);
错误信息告诉你不能复制QObjects。以下是QObjects不可复制的原因:
相关文章:
- 分段错误 - 读取初始化指针的数组
- 初始化指针的常量向量
- 初始化指针或引用成员变量以指向另一个成员
- C++初始化指针/引用/复制细微差别
- 使用无效指针初始化指针声明符的行为是否未定义?
- 在一行中初始化指针(新uint8_t[高度*宽度*3])
- 如何使用可变模板初始化指针?
- 初始化指针时出现写入访问冲突
- C 错误,带有卷曲括号的字面初始化指针
- 重新初始化指针是一种不好的做法吗?
- 初始化指针?C
- 初始化指针向量的向量
- 如何在类函数中正确初始化指针
- C++初始化指针会使应用程序随机崩溃
- 初始化指针结构 - 内存中的外观
- 如何使用struct构造函数在结构中初始化指针阵列
- 在一行中声明并初始化指针到类实例
- 分配数组与初始化指针
- QT 中的非初始化指针
- 使用地址值初始化指针