How to fix a “invalid operands to binary expression” error?

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;
    }
}

1 thought on “How to fix a “invalid operands to binary expression” error?”

Leave a Comment