How do I fix an “ambiguous” function call?

蓝咒 提交于 2019-12-05 13:24:21

问题


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 with different parameters.

How can I tell the compiler which one I want? Aside from a case-specific fix, is there a general rule, such as typecasting, which might solve these kinds of problems?

Edit:

In my case, I tried calling abs() inside of a cout statement, passing in two doubles.

cout << "Amount is:" << abs(amountOrdered-amountPaid);

Edit2:

I'm including these three headers:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

Edit3:

I've finished the program without this code, but in the interest of following through with this question, I've reproduced the problem. The verbatim error is:

Call to 'abs' is ambiguous.

The compiler offers three versions of abs, each taking a different datatype as a parameter.


回答1:


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!




回答2:


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.




回答3:


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>.




回答4:


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) );


来源:https://stackoverflow.com/questions/7549874/how-do-i-fix-an-ambiguous-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!