首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现的`operator<`仍然出现错误-不匹配“运算符<”(操作类型为const StorageFile‘和'const StorageFile')

实现的`operator<`仍然出现错误-不匹配“运算符<”(操作类型为const StorageFile‘和'const StorageFile')
EN

Stack Overflow用户
提问于 2020-06-10 19:58:27
回答 1查看 966关注 0票数 0

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

代码语言:javascript
复制
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< --我已经实现了。编译器会产生以下错误:

代码语言:javascript
复制
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

代码语言:javascript
复制
//...
bool StorageFile::operator <(const StorageFile& storageFile)
{
     return size > storageFile.size;
}
//...

将违规行修改为:

代码语言:javascript
复制
bool operator< (const StorageFile& storageFile) const;

A它提出申诉:

代码语言:javascript
复制
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关键字&定义将相应更新:

The StorageFile.h

代码语言:javascript
复制
 bool operator< (const StorageFile& storageFile) const;

StorageFile.cpp

代码语言:javascript
复制
bool StorageFile::operator<(const StorageFile& storageFile) const
{
     return size > storageFile.size;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-10 20:00:21

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

代码语言:javascript
复制
bool operator< (const StorageFile& storageFile) const;
                                            //  ^^^^^

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

通常情况下,operator<应该作为一个成员来实现。如果对用例有效,也可以编写非会员operator<

编辑:看看您的代码,还不清楚您是否已经定义了operator<。显然,你需要这样做,但它仍然必须是合格的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62312140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档