【发布时间】: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 关键字)
【问题讨论】:
-
请提供minimal reproducible example 来证明您的问题。我的赌注是在损坏的包含树上。
标签: c++ qt operator-overloading operator-keyword qmap