Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c++ - Strange ambiguous call to overloaded function error

I'm trying

void function(int y,int w)
{
    printf("int function");

}


void function(float y,float w)
{
    printf("float function");
}


int main()
{
    function(1.2,2.2);
    return 0;
}

I get an error error like..

error C2668: 'function' : ambiguous call to overloaded function

and when I try to call function(1.2,2) or function(1,2.2) it is printing as "int function"

Please clarify when will the function(float y,float w) be called?

question from:https://stackoverflow.com/questions/16602175/strange-ambiguous-call-to-overloaded-function-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look at the error message from gcc:

a.cpp:16: error: call of overloaded ‘function(double, double)’ is ambiguous
a.cpp:3: note: candidates are: void function(int, int)
a.cpp:9: note:                 void function(float, float)

A call to either function would require truncation, which is why neither is preferred over the other. I suspect you really want void function(double y,double w). Remember that in C/C++, the default floating-point type for literals and parameter passing is double, NOT float.

UPDATE

If you really don't want to change the function signature from float to double, you can always use literals that are typed as float. If you add the suffix f to the floating point numbers, they will be typed float.

Your examples would then be function(1.2f, 2f) and function(1, 2.2f).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...