c++qtqmap

Using QMap and getting compile error messages


I am trying to use a "QMap", in the class prototype:

    QMap<QString, TargetsInfo*> m_targets;

In an access method I have:

    TargetsInfo* TargetsModel::addTarget(int division, int camera, int map) const {
        TargetsInfo* target = getTarget(division, camera, map);

        if (target == nullptr) {
            const QString key = makeKey(division, camera, map);
            target = new TargetsInfo();

            if ( target != nullptr ) {
                m_targets.insert(key, target);
            }
        }
        return target;
    }

    TargetsInfo* TargetsModel::getTarget(int division, int camera, int map) const {
        const QString key = makeKey(division, camera, map);
        QMap<QString, TargetsInfo*>::iterator itr = m_targets.find(key);
        return (its == m_targets.end()) ? nullptr : itr.value();
    }

When I compile I get the following errors which I am struggling to see what is wrong:

    C2663: 'QMap<QString, TargetInfo *>::insert': 2 overloads have no legal conversion for 'this' pointer
    C2440: 'initialising': cannot convert from 'QMap<QString, TargetInfo *>::const_iterator' to 'QMap::<QString, TargetInfo *>::iterator'
    No constructor could take the source type, or constructor overload resolution was ambiguous

Solution

  • For the second error change

    QMap<QString, TargetsInfo*>::iterator itr = ...
    

    to

    QMap<QString, TargetsInfo*>::const_iterator itr = ...
    

    Your getTarget method is const so m_targets.find returns a const iterator (otherwise you could change m_targets inside your supposedly const method).

    For the first error, remove const from your addTarget method. Obviously a method which adds items to m_targets should not be const.