在QMap中插入QObject * -不能初始化或传递指针



我设置了两个类,InputFileInputStream。两者都继承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不可复制的原因:

最新更新