minary minary - 1 month ago 4x
C++ Question

Operator priority with operator overload?

I used operator overloading for my own Bignum header, and there are some operator priority problem.

Compiler says there is some error when I do bignum+int.
(My Bignum class name is 'bignum'. Don't mind that)

Here is my class definition:

operator long long(void) const {
return atoll(num.c_str());
operator +(bignum b) {
return c;

And here is the case that error happens:

bignum a(1);
int b=1;
bignum c = a+b; //this is the case


line 7 : IntelliSense: "+" More than one of the operators is
consistent with the operand.
Built-in operators "arithmetic +
Function "minary::bignum::operator+(minary::bignum
The operand format is minary::bignum +
int. c:\Users\Secret\Documents\Visual Studio
2013\Projects\Calculator\Calculator\Source.cpp 11 3 Calculator

Thanks in advance.


The easiest approach is to make the conversion to integers explicit: many implicit conversions cause problems anyway. Sometimes implicit conversions are useful but if you want to deal with mixed type arithmetic they tend to be more a problem than help:

class bignum {
    // ...
    explicit operator long long() const { ... }
    // ...

Making the conversion operator explicit is a C++11 feature. Your class also seems to have an implicit conversion from integral types to bignum, i.e., a corresponding constructor. Prior to C++11 you could only make these constructors explicit. This may be another option to deal with the ambiguity but it would have the effect that the conversion to long long and the built-in integer addition is used. My guess that you want a bignum as a result which requires that there is no suitable conversion to an integral type.

Note that the question has nothing to do with operator priority: for any given expression the compiler determines which overloads are the best fit (roughly: require the least amount of implicit conversions). If it finds multiple equally good candidates it considers the program to be ambiguous and asks for the ambiguity to be sorted out.