gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:23 25 4
gpt4 key购买 nike

我有一个 QList<MyPoint*> l其中 MyPoint是我想做的用户自定义类类型:

 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> )。不过,您必须确保重载赋值运算符和复制构造函数。

如果这变得太昂贵,请考虑将您的类转换为使用 implicit sharing像大多数 Qt 数据类一样,使用 QSharedDataQSharedDataPointer类。

关于c++ - 如何为指针的 QList 编写自定义比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35829713/

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