C++ ambiguous overload for ‘operator ’

前端 未结 3 621
你的背包
你的背包 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.

提交回复
热议问题