当我运行该程序时,它会产生错误[Error] call of overloaded 'add(double, double, double)' is ambiguous
。
这是为什么?我的意思是函数参数具有不同的数据类型,这实际上是函数重载,那么为什么会出错?
但是,当浮点数被double替换时,它可以正常工作。
#include<iostream>
using namespace std;
void add(){
cout<<"I am parameterless and return nothing";
}
int add( int a, int b ){
int z = a+b;
return z;
}
int add(int a, int b, int c){
int z = a+b+c;
return z;
}
int add(float a, float b, float c)
{
int z = a +b + c;
return z;
}
int main()
{
cout<<"The void add() function -> ";
add();
cout<<endl;
cout<<"add(2,3) -> "<<add(2,3)<<endl;
cout<<"add(2,3,4) -> "<<add(2,3,4)<<endl;
cout<<"add(2.1,4.5) -> "<<add(2.8,3.1,4.1)<<endl;
return 0;
}
因为你调用使用功能double
文字,以及那些可以被转换为任何int
或到float
,编译器不知道它应该选择。
最简单的解决方案是改为使用float
文字调用该函数:
add(2.8f,3.1f,4.1f)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句