For checking equality in a simple array, i’ve the following;
int a[4] = {9,10,11,20};
if(a[3]== 20){
cout <<"yes"<< endl;
}
However, when I create an array of type class, and try and check equality I get error;
Human is a class with private variables for name, age, gender etc, and
get and set functions for these variables.humanArray has size 20
void Animal::allocate(Human h){
for (int i =0; i<20; i++){
if(humanArray[i] == h){
for(int j = i; j<size; j++){
humanArray[j] = humanArray[j +1];
}
}
}
}
I get following error;
error: no match for 'operator==' in '((Animal*)this)->Animal::humanArray[i] == h'|
I could pass in the index and Human, and check against index number. However, is there a way to check if two elements are same? I don’t wish to check say ‘Human name’ against human name, since for some parts my human will not have a name.
In order to make the syntax
legal, you will need to define
operator==for your human class. To do this, you might write a function that looks like this:Inside this function, you would do a field-by-field comparison of
lhsandrhsto see if they were equal. From this point forward, any time that you try to compare any two humans by using the==operator, C++ will automatically call this function for you to make the comparison.Hope this helps!