How do I fix an “ambiguous” function call?

后端 未结 4 1118
礼貌的吻别
礼貌的吻别 2021-02-18 14:59

I\'m working on a C++ program for class, and my compiler is complaining about an \"ambiguous\" function call. I suspect that this is because there are several functions defined

相关标签:
4条回答
  • 2021-02-18 15:32

    What's happened is that you've included <cstdlib> (indirectly, since it's included by iostream) along with using namespace std;. This header declares two functions in std with the name abs(). One takes and returns long long, and the other returns long. Plus, there's the one in the global namespace (that returns int) that comes from <stdlib.h>.

    To fix: well, the abs() that takes double is in <cmath>, and that will actually give you the answer you want!

    0 讨论(0)
  • 2021-02-18 15:37

    Try using fabs defined in <cmath>. It takes float, double and long double as arguments. abs is defined both in <cmath> and <cstdlib>. The difference is abs(int), abs(long) and abs(long long) are defined in <cstdlib> while other versions are defined in <cmath>.

    0 讨论(0)
  • 2021-02-18 15:41

    Not sure why this isn't calling the int version of abs but you could try type casting the expression (amountOrdered - amountPaid) as int i.e.

    cout <<"Amount is: "<< abs( (int)(amountOrdered - amountPaint) );
    
    0 讨论(0)
  • 2021-02-18 15:50

    The abs function included by <cstdlib> is overloaded for int and long and long long. Since you give a double as the argument, the compiler does not have an exact fit, so it tries to convert the double to a type that abs accepts, but it does not know if it should try to convert it to int, long, or long long, hence it's ambiguous.

    But you probably really want the abs that takes a double and returns a double. For this you need to include <cmath>. Since the double argument matches exactly, the compiler will not complain.

    It seems that <cstdlib> gets included automatically when you include the other headers which should not happen. The compiler should have given error: ‘abs’ was not declared in this scope or something similar.

    0 讨论(0)
提交回复
热议问题