سؤال

I have a class TypeData and want to store objects of that type in a QMap then I want to get a specific object out of the map and call a memberfunction of this object. But when I try to do that i get the following error message:

error C2662: 'TypeData::write': cannot convert 'this' pointer from 'const TypeData' to 'TypeData &'

here are the relevant code snippets:

QMap<QString, TypeData> typeDataList;

typeDataList.insert(currentID, temp);

typeDataList.value(currentID).write();

Can anyone tell what I', doing wrong here? And how I could fix this?

هل كانت مفيدة؟

المحلول

QMap::value returns a const T, i.e. a both a copy of the element in the map, and a non-modifyable one. Your write() method is probably not const, thus calling write() on the const T is not allowed. If value returned just T, it would work, but any changes write() does to the temporary object would be lost right away. (As the copy is destroyed right after).

So you can either make write() const if it doesn't modify the TypeData. That's preferable, if possible.

Alternatively you can do:

typeDataList[currentID].write() // modifies the object in the map but also will insert a TypeData() if there is no entry for key currentID yet.

or, more verbose but without inserting a new element if none is found:

QMap<QString,TypeData>::Iterator it = typeDataList.find(currentID);
if ( it != typeDataList.constEnd() ) {
    it->write();
} else {
    // no typedata found for currentID
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top