开发者

Overloaded Types Mismatch

开发者 https://www.devze.com 2023-02-16 01:27 出处:网络
How does overloading work in C++?I defined two overloaded functions one takes a float and the other takes开发者_高级运维 an integer:

How does overloading work in C++? I defined two overloaded functions one takes a float and the other takes开发者_高级运维 an integer:

void myFunc(float a) { ... }
void myFunc(int a) { ... }

BUT I cannot use the int version whenever I try to pass an integer the compiler panic about an ambiguous call. I only can use the float version. Weird?

Thanks.


void f(int x)
{}
void f(float x)
{}

int main()
{
   int a = 2;
   f(a); //will unambiguously call f(int)
   f(3); //will unambiguously call f(int)
}

Why? Because int->int is an exact match which is always better than int->float, which is a match with standard conversion. if this isn't the behaviour you're experiencing then your compiler is a bad compiler. In any case, overload resolution rules are a bit complicated. This link might help shed light on it


BUT I cannot use the int version whenever I try to pass an integer the compiler panic about an ambiguous call.

No. It cannot complain that if you call it as,

int i=10;
myFunc(i); //myFunc(int) gets called!
myFunc(1); //again myFunc(int) gets called!

See yourself here : http://ideone.com/RI33a

No ambiguity!


You're probably unintentionally calling it with a char or double and the compiler can't figure out which version you actually want.

0

精彩评论

暂无评论...
验证码 换一张
取 消