如何重载"<"运算符以比较同一类的对象?

How do you overload the '<' operator to compare between objects of the same class?

本文关键字:一类 比较 对象 重载 何重载 lt 运算符      更新时间:2023-10-16

现在我有一个类项目

class Item{
public:
short p;        //profit
short w;        //weight
bool *x;        //pointer to original solution variable
void set_values (short p, short w, bool *x);
};

我需要比较两个不同的实例,以便它检查每个实例的值并返回真/假

if (Item a < Item b){
//do something
}

我该怎么做?我一直在阅读 cpp偏好,但我真的不知道该怎么做。

很简单,

bool Item::operator<(const Item& other) const {
// Compare profits
return this->p < other.p;
}

若要将左侧pw与右侧进行比较pw使用以下代码:

class MyClass
{
public:
short p;
short w;
friend bool operator<(const MyClass& lhs, const MyClass& rhs)
{
return lhs.p < rhs.p && lhs.w < rhs.w;
}
};

例如,如果要比较 p,代码应如下所示:

class Item {
private:
...
public:
friend bool operator < (const Item& lhs, const Item& rhs) {
return lhs.p < rhs.p;
}
};