【问题标题】:Calling Memberfunctions out of a QMap从 QMap 中调用成员函数
【发布时间】:2015-11-06 16:07:39
【问题描述】:

我有一个 TypeData 类,想将该类型的对象存储在 QMap 中,然后我想从映射中获取特定对象并调用该对象的成员函数。 但是当我尝试这样做时,我收到以下错误消息:

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

这里是相关代码sn-ps:

QMap<QString, TypeData> typeDataList;

typeDataList.insert(currentID, temp);

typeDataList.value(currentID).write();

谁能告诉我在这里做错了什么?我该如何解决这个问题?

【问题讨论】:

    标签: c++ qt qmap


    【解决方案1】:

    QMap::value 返回一个const T,即既是地图中元素的副本,也是不可修改的元素。您的 write() 方法可能不是 const,因此不允许在 const T 上调用 write()。如果值只返回T,它会起作用,但是 write() 对临时对象所做的任何更改都会立即丢失。 (因为副本随即被销毁)。

    因此,如果它不修改 TypeData,您可以将 write() 设为 const。 如果可能的话,这是最好的。

    您也可以这样做:

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

    或者,更详细但如果没有找到则不插入新元素:

    QMap<QString,TypeData>::Iterator it = typeDataList.find(currentID);
    if ( it != typeDataList.constEnd() ) {
        it->write();
    } else {
        // no typedata found for currentID
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      相关资源
      最近更新 更多