本文介绍了我如何重载功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试...

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

并且当我尝试调用function(1.2,2)或function(1,2.2)时,它正在打印为"int函数".

请澄清..何时函数(float y,float w)?

and when I''m trying 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)?

推荐答案

您的示例将是function(1.2f, 2f)function(1, 2.2f).


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)



调用这两个函数都需要截断,这就是为什么两个函数都不是另一个函数的原因.我怀疑您真的想要void function(double y,double w).请记住,在C/C ++中,用于文字和参数传递的默认浮点类型是double,而不是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.


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



其次,按照我喜欢的方式,它始终有效(也可以用于C ++的默认转换和升级).
对于int:-



Secondly, and the way I like to do it, It always works (and can also be used for C++''s default conversion and promotion).
For int:-

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



对于浮动:-



For Float:-

int main()
{
float a=1.2, b=2.2;
	function(a,b);
	return 0;
}



因此,不要使用实际的DIGITS.最好先将它们声明为类型,然后再声明为重载!

现在看,如果以(1.2,2)或(1,2.2)的形式发送它,则编译器可以简单地将其发送到int函数,它将起作用.
但是,要将其发送到float函数,编译器必须将2提升为float.促销仅在找不到匹配项时发生.

参考:-
使用C ++的计算机科学
住田Arora
章:函数重载



So instead of using actual DIGITS. It is better to declare them as a type first, then overload!

See now, if you send it as (1.2,2) or (1,2.2) then compiler can simply send it to the int function and it would work.
However, to send it to the float function the compiler would have to promote 2 to float. Promotion only happens when no match is found.

Refer:-
Computer Science with C++
Sumita Arora
Chapter: Function Overloading


这篇关于我如何重载功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 19:23