[英]How to override qHash() function?
我想使用自定义对象的QSet
。 从文档中,我发现:
QSet 的值数据类型必须是可赋值的数据类型。 例如,您不能将 QWidget 存储为值; 相反,存储一个 QWidget *。 此外,该类型必须提供 operator==(),并且还必须有一个全局 qHash() 函数,该函数返回键类型参数的哈希值。 有关 qHash() 支持的类型列表,请参阅 QHash 文档。
以下代码表示我想使用的struct
:
typedef struct ShortcutItem
{
QString shortcutName; // A shortcut name
QString explaination; // A shortcut explaination
bool editable; // Is editable
KeySequence sequence; // A list of key values defining a shortcut
ShortcutItem(void) {}
ShortcutItem(QString& name, QString& description, bool enabled, KeySequence seq) : shortcutName(name), explaination(description), editable(enabled), sequence(seq) {}
ShortcutItem(const ShortcutItem& other) : shortcutName(other.shortcutName), explaination(other.explaination), editable(other.editable), sequence(other.sequence) {}
bool ShortcutItem::operator==(const ShortcutItem& other) const { return shortcutName == other.shortcutName; }
} ShortcutItem;
到目前为止,我已经重载==
运算符,但无法确定如何处理qHash()
函数。
任何帮助,请。
PS我看到这篇文章,无法决定该怎么做。
就我从您的代码中看到的而言,您的散列函数应该如下所示
uint qHash(const ShortcutItem & item)
{
return qHash(item.shortcutName);
}
换句话说,您可以使用可用的重载uint qHash(const QString &key, uint seed = ...)
,将项目成员shortcutName
传递给它,然后只返回其返回值。
您可以将函数原型放在ShortcutItem
结构之后,在其标题中:
uint qHash(const ShortcutItem & item);
以及其实现文件 (.cpp) 中的定义(以上)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.