简体   繁体   中英

No match for operator == error, C++

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.

Thanks!

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

Like this (missing asterisk).

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

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

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM