我缺乏使用c ++的经验,并且在编译器生成二进制表达式的无效操作数
时停滞不前class Animal{
public:
int weight;
};
int main(){
Animal x, y;
x.weight = 33;
y.weight = 3;
if(x != y) {
// do something
}
}
我想使用x并与y进行比较,而不修改主代码中的代码,即(x.weight!= y.weight)。我应该如何从外部类或定义中解决这个问题?
答案 0 :(得分:4)
根据评论中的建议,您需要重载!=
运算符,例如
class Animal{
public:
int weight;
bool operator!=(const Animal &other)
{
return weight != other.weight;
}
};
表达式x != y
就像对此运算符的函数调用,实际上它与x.operator!=(y)
相同。
答案 1 :(得分:4)
或者,您可以将运算符重载添加为非成员:
#include <iostream>
using namespace std;
class Animal{
public:
int weight;
};
static bool operator!=(const Animal& a1, const Animal& a2) {
return a1.weight != a2.weight;
}
int main(){
Animal x, y;
x.weight = 33;
y.weight = 3;
if(x != y) {
cout << "Not equal weight" << endl;
}
else {
cout << "Equal weight" << endl;
}
}