我有一个名为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;
~~~~~^~~~~~即使我已经实现了所需的操作符,为什么它仍然会出现这个错误呢?
更新
添加运算符的定义:
StorageFile.cpp
//...
bool StorageFile::operator <(const StorageFile& storageFile)
{
return size > storageFile.size;
}
//...将违规行修改为:
bool operator< (const StorageFile& storageFile) const;A它提出申诉:
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
bool operator< (const StorageFile& storageFile) const;和StorageFile.cpp
bool StorageFile::operator<(const StorageFile& storageFile) const
{
return size > storageFile.size;
}(请注意两者末尾的const关键字)
发布于 2020-06-10 20:00:21
您的operator<不正确。若要允许<在左侧操作数是const对象时工作,还需要对成员operator<进行限定:
bool operator< (const StorageFile& storageFile) const;
// ^^^^^请注意,map通常需要将const键与<进行比较,这就是错误消息所暗示的。
通常情况下,operator<应该作为一个成员来实现。如果对用例有效,也可以编写非会员operator<。
编辑:看看您的代码,还不清楚您是否已经定义了operator<。显然,你需要这样做,但它仍然必须是合格的。
https://stackoverflow.com/questions/62312140
复制相似问题