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); 不知道哪错了,哪位大侠教教我,
叩谢!
这两个函数对于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来默认地作为浮点型数的存储方式中看出)。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值