Benjamin Kovach
Benjamin Kovach

Reputation: 3260

No match for operator == error in !(this == h)

This is really bugging me. I'm working on overloading the comparison operators in C++, and I'm getting a weird error that I'm not sure how to correct.

The code I'm working with looks like this:

bool HugeInt::operator==(const HugeInt& h) const{
    return h.integer == this->integer;
}

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(this == h);
}

where integer is a short [30]

The == overloading works fine. But when I try to use it in the != body, it tells me that == has not been defined. I'm new to C++, so any tips are welcome.

Upvotes: 2

Views: 437

Answers (5)

Ivan Vergiliev
Ivan Vergiliev

Reputation: 3841

You're trying to compare a pointer and an instance. this is a pointer to the current object, you need to dereference it first.

Anyway, you've mentioned that integer is an array of shorts. That probably means you shouldn't compare it with == - you should just compare all the elements manually (after, of course, you check that the number of elements in the arrays is the same, in case they can be filled partially). Or you could use a vector as Luchian suggested - it has a well-defined operator==.

Upvotes: 12

Dave Holliday
Dave Holliday

Reputation: 21

Overloaded operators work on objects not pointers (like this). You should dereference this in your inequality operator:

return !(*this == h);

You could alternatively structure it like:

return( !operator==( h ) );

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258548

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(this == h);
}

should be

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(*this == h);
}

Also, if integer is of type short[30], the comparison won't do what you expect. You'll need to compare element by element, if that's what you want.

Also, might I suggest using a std::vector<short> instead of a raw array?

Upvotes: 2

john
john

Reputation: 87944

Like this (missing asterisk).

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(*this == h);
}

Upvotes: 5

Magnus Hoff
Magnus Hoff

Reputation: 22089

this has type HugeInt*, but you use it as if it is HugeInt&.

Use return !(*this == h); instead :)

Upvotes: 4

Related Questions