Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ambiguous overload for ‘operator ’

I'v read several posts here about this kind of errors, but I wasn't able to solve this one... Has soon I define the operator int and the function f, fails to compile. I tested several things by I wasn't able to solve the issue.... Thanks

ex1.cpp: In function ‘int main(int, char**)’:
ex1.cpp:35:13: error: ambiguous overload for ‘operator+’ in ‘a + 4’
ex1.cpp:35:13: note: candidates are:
ex1.cpp:35:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)
ex1.cpp:38:13: error: ambiguous overload for ‘operator+’ in ‘4 + a’
ex1.cpp:38:13: note: candidates are:
ex1.cpp:38:13: note: operator+(int, int) <built-in>
In file included from ex1.cpp:3:0:
Fraccao.h:41:9: note: Fraccao operator+(const Fraccao&, const Fraccao&)

The class:

class Fraccao {
    int numerador;
    int denominador;

public:
    Fraccao(int num = 0, int deno = 1) : numerador(num), denominador(deno) {}

    Fraccao & operator+=(const Fraccao &fra);

    Fraccao & operator*=(const Fraccao &fra);

    operator int() const;

    const Fraccao & operator++();
    const Fraccao operator++(int);

    string getAsString() const;
};

Fraccao operator +(const Fraccao &a, const Fraccao &b);
ostream & operator<<(ostream & saida, const Fraccao & fra);

And on my main:

void func(int n) {
    cout << n; // 
}

int main(int argc, char** argv) {
    //...
    d = a + b;
    const Fraccao h(7, 3);
    func(h);

    return 0;
}
like image 386
Godinho Avatar asked Nov 06 '13 17:11

Godinho


1 Answers

You have several options to fix your problem:

  • Forbid implicit conversion from int to Fraccao: Make the constructor explicit.
  • Forbid implicit conversion from Fraccao to int: Make the conversion operator explicit.

  • Convert manually on the callers side, given Fraccao f; int i; either int(f)+i or f+Fraccao(i).

  • Provide additional overloads to resolve the ambiguity:

Fraccao operator +(const Fraccao &a, const Fraccao &b);
Fraccao operator +(const int a, const Fraccao &b);
Fraccao operator +(const Fraccao &a, const int b);

The latter probably means you also want:

Fraccao & operator+=(const Fraccao &fra);
Fraccao & operator+=(const int i);

And finally, if you want the latter, you can use libraries like Boost.Operators or my df.operators to support you and avoid writing the same forwarders over and over again.

like image 71
Daniel Frey Avatar answered Sep 29 '22 12:09

Daniel Frey