Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...