gpt4 book ai didi

c++ - 如何覆盖 qHash() 函数?

转载 作者:行者123 更新时间:2023-12-02 10:21:59 25 4
gpt4 key购买 nike

我想使用 QSet自定义对象。从文档中,我发现:

QSet's value data type must be an assignable data type. You cannot, for example, store a QWidget as a value; instead, store a QWidget *. In addition, the type must provide operator==(), and there must also be a global qHash() function that returns a hash value for an argument of the key's type. See the QHash documentation for a list of types supported by 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()功能。

任何帮助,请。

附言我看到了 post并且无法决定要做什么。

最佳答案

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

uint qHash(const ShortcutItem & item)
{
return qHash(item.shortcutName);
}

换句话说,您可以使用可用的重载 uint qHash(const QString &key, uint seed = ...) , 传递项目成员 shortcutName给它,然后返回它的返回值。

您可以将函数原型(prototype)放在 ShortcutItem 之后结构,在它的标题中:
uint qHash(const ShortcutItem & item);

及其实现文件(.cpp)中的定义(上图)。

关于c++ - 如何覆盖 qHash() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com