已实现的 `operator<` 仍然给出错误 - 不匹配 'operator <'(操作类型是 const StorageFile' 和 'const StorageFile')

KGC*_*beX 0 c++ qt operator-overloading qmap operator-keyword

我有一个名为的自定义结构StorageFile,其中包含有关存储在数据库中的文件的一些信息。

class StorageFile : public QObject {
     Q_OBJECT

  public:
     int ID = -1;
     QString filename;
     QString relativeLocation;
     MediaType type;
     QDateTime dateLastChanged;
     quint64 size;
     QString sha256;
     //...

     explicit StorageFile(QObject* parent = nullptr);
     StorageFile(const StorageFile& other);
     StorageFile& operator= (const StorageFile& other);
     bool operator< (const StorageFile& storageFile);      < --------- implemented operator
     bool operator== (const StorageFile& storageFile);

     //...
}
Run Code Online (Sandbox Code Playgroud)

我将这些 StorageFile 对象添加到QMap,并且QMap 需要实施operator< - 我有。编译器给出以下错误:

F:\Qt\Qt5.13.1\5.13.1\mingw73_32\include\QtCore/qmap.h:71:17: error: no match for 'operator<' (operand types are 'const StorageFile' and 'const StorageFile')
     return key1 < key2;
            ~~~~~^~~~~~
Run Code Online (Sandbox Code Playgroud)

即使我已经实现了所需的运算符,为什么它仍然会出现此错误?


更新

添加运算符的定义:

存储文件

//...
bool StorageFile::operator <(const StorageFile& storageFile)
{
     return size > storageFile.size;
}
//...
Run Code Online (Sandbox Code Playgroud)

将违规行修改为:

bool operator< (const StorageFile& storageFile) const;
Run Code Online (Sandbox Code Playgroud)

它抱怨:

path\to\project\libs\storagefile.h:33: error: candidate is: bool StorageFile::operator<(const StorageFile&) const
      bool operator< (const StorageFile& storageFile) const;
           ^~~~~~~~
Run Code Online (Sandbox Code Playgroud)

解决方案

正如@cijien 提到的,确保 operator< 具有 const 关键字并且相应地更新定义:

存储文件.h

 bool operator< (const StorageFile& storageFile) const;
Run Code Online (Sandbox Code Playgroud)

StorageFile.cpp

bool StorageFile::operator<(const StorageFile& storageFile) const
{
     return size > storageFile.size;
}
Run Code Online (Sandbox Code Playgroud)

(注意两者末尾的 const 关键字)

cig*_*ien 5

operator<的不正确。要允许<在左侧操作数是const对象时工作,您还需要对成员进行 const 限定operator<

bool operator< (const StorageFile& storageFile) const;
                                            //  ^^^^^
Run Code Online (Sandbox Code Playgroud)

请注意, amap通常要求可以将 const 键与 进行比较<,这是错误消息所暗示的。

这通常operator<是作为成员应该如何实施。operator<如果这适用于您的用例,您也可以编写一个非成员。

编辑:查看您的代码,尚不清楚您是否已定义 operator<。显然,您需要这样做,但它仍然必须是 const 限定的。