C++ ambiguous overload for ‘operator ’

前端 未结 3 629
你的背包
你的背包 2021-02-14 08:38

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 teste

相关标签:
3条回答
  • 2021-02-14 09:16

    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.

    0 讨论(0)
  • 2021-02-14 09:32

    The compiler sees two ways to interpret a + 4. It can convert the 4 to an object of type Fraccao and use operator+(const Fraccao&, const Fraccao&) or it can convert a to type int with the member conversion operator, and add 4 to the result. The rules for overloading make this ambiguous, and that's what the compiler is complaining about. In general, as @gx_ said in a comment, this problem comes up because there are conversions in both directions. If you mark the operator int() with explicit (C++11) the code will be okay.

    0 讨论(0)
  • 2021-02-14 09:34

    You don't seem to have posted the code that actually causes the error. I guess it looks something like

    Fraccao a;
    Fraccao b = a + 4;
    Fraccao c = 4 + a;
    

    The problem is that your class allows implicit conversions both to and from int; so a + 4 could be either

    int(a) + 4
    

    or

    a + Fraccao(4)
    

    with no reason to choose one over the other. To resolve the ambiguity, you could either:

    • make the conversion explicit, as above; or
    • declare either the constructor or the conversion operator (or even both) explicit so that only one (or even neither) conversion can be done implicitly.
    0 讨论(0)
提交回复
热议问题