注:文章内容来源于网络,真实性有待确认,请自行甄别。
重载函数的问题c++原题是使用重载函数的方法定义两个函数,用来分
发表于:2024-10-24 00:00:00浏览:10次
问题描述:原题是使用重载的方法定义两个函数,用来分别求出两个int型数的点间距离和浮点型数的点间距离。
#include<iostream.h>
#include<math.h>
int distan(int,int);
float distan(float,float);
void main()
{
int distance1;
float distance2;
distance1=distan(1,2);
distance2=distan(1.35,2.78);//出错处
原题是使用重载的方法定义两个函数,用来分别求出两个int型数的点间距离和浮点型数的点间距离。
#include<iostream.h>
#include<math.h>
int distan(int,int);
float distan(float,float);
void main()
{
int distance1;
float distance2;
distance1=distan(1,2);
distance2=distan(1.35,2.78);//出错处
cout<<distance1<<distance2;
}
int distan(int x,int y)
{
int c=abs(x-y);
return c;
}
float distan(float x,float y)
{
float c=abs(x-y);//错误处
return c;
}
d:\vc++ 6.0\myprojects\p1299\p7.cpp(10) : error C2668: 'distan' : ambiguous call to overloaded function
d:\vc++ 6.0\myprojects\p1299\p7.cpp(20) : warning C4244: 'argument' : conversion from 'float' to 'int', possible loss of data
d:\vc++ 6.0\myprojects\p1299\p7.cpp(20) : warning C4244: 'initializing' : conversion from 'int' to 'float', possible loss of data
.请高手帮帮忙指点一下 小弟感激不尽
第一处错误的确如楼上所说,是因为数据类型不明确。由于1.35和2.78会被默认为double型而非float型,而你并没有提供含有double型输入参数的distan函数,因此就给编译器造成困扰,不明白究竟应该转换为int型还是float型。如果你在输入时写成1.35f和2.78f,则表示强制转换为float型,此时就不会报错了。
第20行报的是警告,是因为数据会被截断而导致计算误差,abs函数只支持int型,要计算float型或double型的绝对值则需用fabs函数。因此,这里你只需在abs前面加一个f即可。
栏目分类全部>