【问题标题】:Implemented `operator<` still gives error - no match for 'operator <' (opereate types are const StorageFile' and 'const StorageFile')实施的 `operator<` 仍然给出错误 - 'operator <' 不匹配(操作类型是 const StorageFile' 和 'const StorageFile')
【发布时间】:2020-09-30 08:58:42
【问题描述】:

我有一个名为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,并且 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;
            ~~~~~^~~~~~

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


更新

为操作符添加定义:

存储文件.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

StorageFile.h

 bool operator< (const StorageFile& storageFile) const;

和StorageFile.cpp

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

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

【问题讨论】:

标签: c++ qt operator-overloading operator-keyword qmap


【解决方案1】:

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

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

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

这通常是operator&lt; 作为成员应如何实现。如果适合您的用例,您也可以写一个非成员 operator&lt;。

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

【讨论】:

  • 非常感谢,我确实在定义我的代码,认为添加它是没有必要的。按照您的建议进行更改确实解决了我的问题。编辑:它提出了另一个问题
  • 视问题而定,应该是新问题。
  • 好的,很好:) 如果这个答案回答了问题,请继续接受它。
  • @cijien 简单问题 - 很容易忘记(问题已更新解决方案) - 如果您愿意,请将其添加到您的答案中
猜你喜欢
  • 2023-04-07
  • 2022-01-06
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多