C++ 如何修复“二进制表达式的无效操作数”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26378591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix a "invalid operands to binary expression" error?
提问by
I am inexperienced of using c++ and stuck at the point where compiler generates invalid operands to binary expression
我没有使用 c++ 的经验,并停留在编译器为二进制表达式生成无效操作数的地方
class Animal{
public:
int weight;
};
int main(){
Animal x, y;
x.weight = 33;
y.weight = 3;
if(x != y) {
// do something
}
}
I want to use x and compare with y, without modifying code i.e. (x.weight != y.weight)in the main code. How should I approach this problem from external class or definition ?
我想使用 x 并与 y 进行比较,而不修改主代码中的代码,即 (x.weight != y.weight)。我应该如何从外部类或定义解决这个问题?
采纳答案by Sambuca
Alternatively you can add the operator overload as non-member:
或者,您可以将运算符重载添加为非成员:
#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;
}
}
回答by TobiMcNamobi
As suggested in the comments you need to overload the !=
operator, for example
正如评论中所建议的,您需要重载!=
运算符,例如
class Animal{
public:
int weight;
bool operator!=(const Animal &other)
{
return weight != other.weight;
}
};
An expression x != y
is like a function call to this operator, in fact it is the same as x.operator!=(y)
.
表达式x != y
就像是对这个运算符的函数调用,实际上它与x.operator!=(y)
.