8

I am inexperienced of using c++ and stuck at the point where compiler generates invalid operands to binary expression

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 ?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

6

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).

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
6

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;
    }
}
Sambuca
  • 1,224
  • 18
  • 30