c++ - 如何覆盖 qHash() 函数?
问题描述
我想使用一个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 = ...)
,将 item 成员传递shortcutName
给它,然后返回它的返回值。
您可以将函数原型放在ShortcutItem
结构之后,在其标题中:
uint qHash(const ShortcutItem & item);
及其实现文件(.cpp)中的定义(上图)。
推荐阅读
- .net - 检查 autofac 中间件中的构造函数参数
- git - GIT:损坏的文件不允许我签出其他分支
- sql - Postgres:将文本 [] 列转换为不同的字符
- google-apps-script - 如何将 PDF 文件从 Google Drive 附加到附件阵列?
- openedge - 执行 .p 文件后,未使用 proenv 在 test.out 文件中获取输出
- azure-cognitive-search - 认知搜索刻面存储需求
- r - 打印回归树时出现问题,“cat(x, ..., sep = sep) 中的错误:参数 1(类型 'list')不能由 'cat' 处理”
- r - 从多列中选择组中的值
- javascript - 将对象转换为类实例
- icloud - iCloud GameKit 40 请求/秒限问题