如何为指针的 QList 编写自定义比较器?

How to write a custom comparator for a QList of pointers?

我有一个 QList<MyPoint*> l,其中 MyPoint 是用户自定义的 class 类型,我想在其中执行以下操作:

 QList<MyPoint*> l;
 MyPoint *a = new MyPoint(2, 4);
 MyPoint *b = new MyPoint(4, 8);
 MyPoint *c = new MyPoint(2, 4);
 l << a << b;

然后:

l.contains(c); //true

我试过重载 == 运算符,正如 doc 所说:

This function requires the value type to have an implementation of operator==().

尝试了不同的方法,但似乎都没有达到预期效果。

这是我目前试过的代码:

class MyPoint
{
public:
    int x, y;

    MyPoint(int x, int y)
        : x(x),
          y(y)
    {
    }

    bool operator == (const MyPoint &other) const
    {
        return other.x == this->x && other.y == this->y;
    }

    bool operator == (const MyPoint *other) const
    {
        return true;
    }
};

bool operator == (const MyPoint &a, const MyPoint &b)
{
    return a.x == b.x && a.y == b.y;
}

我试过类似的方法:

bool operator == (const MyPoint *a, const MyPoint *b)
{
    return a.x == b.x && a.y == b.y;
}

但我读到这是不可能的...我知道 (*a == *c) 是正确的,但我希望它影响 contains() 行为,以便它使用我自己的比较器进行比较。

operator== 重载仅适用于 MyPointer 对象的指针地址,不适用于对象本身。

与其拥有 MyPointer* 对象列表,不如尝试创建 MyPointer 对象列表(即 QList<MyPointer>)。不过,您必须确保重载赋值运算符和复制构造函数。

如果这变得太昂贵,请考虑将您的 class 转换为使用 implicit sharing,就像大多数 Qt 数据 classes 通过使用 QSharedDataQSharedDataPointer classes.