gpt4 book ai didi

c++ - 如何重载 '<' 运算符以比较同一类的对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:01 25 4
gpt4 key购买 nike

现在我有一个类项目

   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);

};

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

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

我该怎么做?我一直在阅读 cppreference,但我真的不明白该怎么做。

最佳答案

很简单,

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

关于c++ - 如何重载 '<' 运算符以比较同一类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752763/

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