6 c++ variables pointers definition
我缺乏使用c ++的经验,并且在编译器为二进制表达式生成无效操作数的地方停留
class Animal{
public:
int weight;
};
int main(){
Animal x, y;
x.weight = 33;
y.weight = 3;
if(x != y) {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用x并与y进行比较,而不修改主代码中的代码即(x.weight!= y.weight).我应该如何从外部类或定义中解决这个问题?
如注释中所建议,您需要使!=运算符超载,例如
class Animal{
public:
int weight;
bool operator!=(const Animal &other)
{
return weight != other.weight;
}
};
Run Code Online (Sandbox Code Playgroud)
表达式x != y就像对此运算符的函数调用一样,实际上与相同x.operator!=(y)。
或者,您可以将运算符重载添加为非成员:
#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;
}
}
Run Code Online (Sandbox Code Playgroud)