首页 > 解决方案 > 如何覆盖 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我看到了这篇文章,无法决定该怎么做。

标签: c++qtqt5

解决方案


据我从您的代码中可以看出,您的散列函数应该看起来像

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)中的定义(上图)。


推荐阅读