【问题标题】:custom qHash method is not being called未调用自定义 qHash 方法
【发布时间】:2021-12-28 05:05:12
【问题描述】:

我使用 QPoint 作为 QHash 中的键,并且按照文档,我为 QPoint 实现了一个全局 qHash 方法,如下所示:

inline uint qHash(QPoint const &key, uint seed) {
  size_t hash = qHash(QPair<int, int>(key.x(), key.y()), seed);
  qDebug() << hash;
  return hash;
}

我就是这样用的

class HashTest {
  public:
    QHash<QPoint, QColor> hash;
    void addPixel(QPoint pt, QColor color) {
      hash[pt] = color;
    }
}

插入仍然正确发生,但它没有使用我的 qHash 函数。即使我注释掉 qHash 函数,它仍然会插入。考虑到 QPoint 被记录为没有 qHash 函数,这是预期的行为吗?

编辑:最小可重现示例

#include <QDebug>
#include <QGuiApplication>
#include <QHash>
#include <QPoint>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[]) {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

  QHash<QPoint, int> hash;
  QPoint key = QPoint(0, 0);
  hash[key] = 3;
  qDebug() << hash[key]; // 3
}

【问题讨论】:

  • @kiner_shah 对不起,我真的以为我之前的资格。无论如何,这是一个例子
  • 您提供的示例没有在任何地方调用qHash,也没有链接它。
  • 这正是重点。为什么看到 qHash 的这项工作不应该在 QPoint 中实现
  • 如果实现了,但没有记录,那么我不希望我的内联版本能够工作。下面的代码似乎表明了这一点

标签: c++ qt hash hashmap


【解决方案1】:

QPoint 的 qHash 可能没有记录,但 sure is defined:

Q_CORE_EXPORT size_t qHash(QPoint key, size_t seed = 0) noexcept;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-11-17
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多