如何重载"<"运算符以比较同一类的对象?
How do you overload the '<' operator to compare between objects of the same class?
现在我有一个类项目
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;
}
若要将左侧p
和w
与右侧进行比较p
并w
使用以下代码:
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;
}
};
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- 如何创建从同一类继承的不同对象的向量
- shell排序中的交换和比较
- 如何重载"<"运算符以比较同一类的对象?
- 为同一类提供不同比较运算符的最佳策略是什么?
- 同一类下两个对象之间的比较
- 如何比较同一类的两个对象
- 在 if 语句中比较同一类的两个对象
- 比较同一类的两个对象
- 比较同一类的 2 个对象(覆盖 == 运算符)c++