2

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.

1

5 Answers 5

12

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That got it running properly. It's actually an array of shorts; does that make a difference? This is for a small project for a class I'm taking, and it seems like we are just expected to compare one short array to another. Anything more would be probably outside the scope of the class (for now).
No, it won't work with shorts either - it would just check if it is actually the same array. In order to compare the contents, you should iterate and compare every single element.
5

Like this (missing asterisk).

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

Comments

4

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

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

Comments

2
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?

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.