I am compiling some C ++ code of the MegaInt class, which is a positive decimal type class that allows arithmetic operations on huge numbers.
I want to overload the bool statement to allow code like this:
MegaInt m(45646578676547676); if(m) cout << "YaY!" << endl;
This is what I did:
Title:
class MegaInt { public: ... operator bool() const; }; const MegaInt operator+(const MegaInt & left, const MegaInt & right); const MegaInt operator*(const MegaInt & left, const MegaInt & right);
implementation:
MegaInt::operator bool() const { return *this != 0; } const MegaInt operator+(const MegaInt & left, const MegaInt & right) { MegaInt ret = left; ret += right; return ret; }
Now the problem is what I am doing:
MegaInt(3424324234234342) + 5;
This gives me this error:
ambiguous overloading for 'operator +' to 'operator + (const MegaInt &, const MegaInt &) Note: candidates: operator + (int, int) | Note: const megaInt + operator (const MegaInt &, const MegaInt &) |
I do not know why. How does overloaded bool () call the + operator, becomes ambiguous? ΒΈ
Thanks.
Well, everyone gave me great answers, unfortunately, none of them seemed to completely solve my problem.
Both void * and Idoom Safe Bool work. Except for one tiny problem, I hope there is a workaround:
When comparing with 0 as:
if (aMegaInt == 0)
The compiler returns an ambiguous overload error again. I understand why: he does not know whether we are comparing the values ββ0 with false or with MegaInt. However, in this case, I would like it to be translated into MegaInt (0). Is there any way to force this?
Thanks again.
c ++ operator-overloading boolean
Didier A.
source share