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

Implemented `operator<` still gives error - no match for 'operator <' (opereate types are const StorageFile' and 'const StorageFile')

我有一个名为 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);

     //...
}

我正在将这些 StorageFile 对象添加到要实施的 QMap, and the QMap requires the operator< - 我有。编译器给出以下错误:

F:\Qt\Qt5.13.1.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;
            ~~~~~^~~~~~

虽然我实现了要求的运算符,为什么还是报错?


更新

为运算符添加定义:

StorageFile.cpp

//...
bool StorageFile::operator <(const StorageFile& storageFile)
{
     return size > storageFile.size;
}
//...

将违规行修改为:

bool operator< (const StorageFile& storageFile) const;

它抱怨:

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

解决方案

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

StorageFile.h

 bool operator< (const StorageFile& storageFile) const;

StorageFile.cpp

bool StorageFile::operator<(const StorageFile& storageFile) const
{
     return size > storageFile.size;
}

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

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

bool operator< (const StorageFile& storageFile) const;
                                            //  ^^^^^

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

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

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