实现的`operator<`仍然给出错误--没有匹配的'operator<'(opereate类型是const StorageFile'和'const StorageFile')

问题描述 投票:0回答:1

我有一个自定义结构,名为 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对象添加到一个 QMapQMap 需要操作员< 要实现--我已经实现了。编译器给出了以下错误。

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;
            ~~~~~^~~~~~

即使我已经实现了所需的运算符,为什么还是会出现这个错误?


更新

添加操作者的定义。

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 关键字 & 定义也相应更新。

这个 存储文件.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个回答
4
投票

你的 operator< 是不正确的。要允许 < 当左手操作数是一个 const 对象,你需要对成员的 operator< 也是。

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

请注意,a map 通常会要求const键可以和 <这就是错误信息所暗示的。

一般来说,这就是 operator< 应该作为成员来实现。你也可以写一个非成员的 operator< 如果这对你的用例有效的话。

编辑: 看了一下你的代码,不清楚你是否有 确定的 operator< 根本不可能。显然,你需要这样做,但它仍然必须是const-qualified的。

© www.soinside.com 2019 - 2024. All rights reserved.