我没有使用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)。我应该如何从外部类或定义中解决此问题?
或者,您可以将运算符重载添加为非成员:
#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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句