c++函数重载遇到了问题
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int orange(int a,int b);
double orange(float a,float b);
string orange(string a,string b);
int main(){
int n=orange(3,4);
cout<<n<<endl;
double d=orange(3.4,4.7);
cout<<d<<endl;
string str=orange("aa","bbb");
cout<<str<<endl;
system("pause");
return 0;
}
int orange(int a,int b){
int c;
return c=a+b;
}
double orange(float a,float b){
double c=a+b;
return c;
}
string orange(string a,string b){
string c=a+b;
return c;
}
编译器报错:ambiguous call to overloaded function 行11
就是这一行double d=orange(3.4,4.7); 不知道哪错了,哪位大侠教教我,
叩谢!
参考答案:int orange(int a,int b);
double orange(float a,float b);
这两个函数对于double d=orange(3.4,4.7);中的传入参数3.4和4.7和以上2个函数原形都匹配,因为他们都是浮点常量,而浮点常量在编译器中一般都是以double的形式来存储的,在C++中你可以通过包含头文件<typeinfo>来看出:
#include <typeinfo>
#include <iostream>
using namespace std;
int main()
{
cout << "type of 3.14: " << typeid(3.14).name() << endl;
cout << "type of 3.14f: " << typeid(3.14f).name() << endl;
}
所以它们二者从double到int和float类型都可以进行隐式转换为其各自参数的对应类型,如:
int a = 3;
float b = 4.4;
double c = 5.5;
b = a; // 合法,隐式转换
a = c; // 合法,隐式转换,但数据可能被截断
b = c; // 合法,隐式转换,但数据可能被截断
所以编译器报错ambiguous不明确,因为它不知道应该调用哪个函数。
解决办法一:
如二楼所说,可以在数字后标明后缀来表示该数字的类型为float,如:
double d=orange(3.4f,4.7f);
解决方法二:
把
double orange(float a,float b)
改为
double orange(double a,double b)。
另外推荐使用double类型来表示浮点数,因为double类型所能表示的数字的精度不仅比float高,而且在绝大多数机器的绝大多数情况下运行速度比float要快的多,而且所占用的空间也不比float大多少(这可以从你的编译器优先选择double而不是float来默认地作为浮点型数的存储方式中看出)。