[英]How to fix a “invalid operands to binary expression” error?
我缺乏使用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)。 我應該如何從外部類或定義中解決這個問題?
正如評論中所建議的那樣,您需要重載!=
運算符,例如
class Animal{
public:
int weight;
bool operator!=(const Animal &other)
{
return weight != other.weight;
}
};
表達式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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.