定义:用同样的名字再定义一个有着不同参数但有着同样用途的函数,可以是参数个数上的不同,也可以是参数数据类型上的不同
#include <iostream>
using namespace std;
void convertTemperature(double tempIn, char typeIn);
void convertTemperature(int tempIn, char typeIn); //函数重载,重新定义数据类型
int main()
{
double tempIn;
char typeIn;
int tempInInt;
cout << "请以[xx.x C]或者[xx.x F]格式输入一个温度: " <<endl;
cin >> tempIn >>typeIn;
cin.ignore(100, '\n');
cout <<endl;
convertTemperature(tempIn, typeIn);
cout << "请以[xx.x C]或者[xx.x F]格式输入一个温度: " <<endl;
cin >> tempInInt >>typeIn;
cin.ignore(100, '\n');
cout <<endl;
convertTemperature(tempInInt, typeIn); //重载函数
return 0;
}
void convertTemperature(double tempIn, char typeIn)
{
//华氏温度=摄氏温度*9.0/5.0+32
const unsigned short ADD_SUBTRACT = 32; //静态变量
const double RATIO = 9.0 / 5.0;
float tempOut;
char typeOut;
switch (typeIn)
{
case 'C':
case 'c':
tempOut = tempIn * RATIO + ADD_SUBTRACT;
typeOut = 'F';
typeIn = 'C';
break;
case 'F':
case 'f':
tempOut = (tempIn - ADD_SUBTRACT) / RATIO;
typeOut = 'C';
typeIn = 'F';
break;
default:
typeOut = 'E';
break;
}
if (typeOut != 'E')
{
cout << tempIn << typeIn
<< " = " << tempOut
<< typeOut << endl;
}
else
{
cout << "输入错误!" << endl;
}
cout << "请输入任何字符结束程序!" << endl;
cin.get();
}
void convertTemperature(int tempIn, char typeIn) //函数重载,重新定义数据类型
{
//华氏温度=摄氏温度*9.0/5.0+32
const unsigned short ADD_SUBTRACT = 32; //静态变量
const double RATIO = 9.0 / 5.0;
int tempOut;
char typeOut;
switch (typeIn)
{
case 'C':
case 'c':
tempOut = tempIn * RATIO + ADD_SUBTRACT;
typeOut = 'F';
typeIn = 'C';
break;
case 'F':
case 'f':
tempOut = (tempIn - ADD_SUBTRACT) / RATIO;
typeOut = 'C';
typeIn = 'F';
break;
default:
typeOut = 'E';
break;
}
if (typeOut != 'E')
{
cout << tempIn << typeIn
<< " = " << tempOut
<< typeOut << endl;
}
else
{
cout << "输入错误!" << endl;
}
cout << "请输入任何字符结束程序!" << endl;
cin.get();
}
课后作业:
1、为什么不能通过返回值不同来重载函数(方法)?
C++调用一个函数是可以忽略其返回值的,这种情况下编译器就无法根据返回值类型来确定调用哪一个函数。所以,重载不能用返回值类型来区别。
2、利用重载函数的方法设计一个程序,该程序通过函数“calc()”进行计算并返回显示结果。
---当传入一个参数时,计算该参数的平方值
---当传入两个参数时,计算两个参数的积
---当传入三个参数时,计算三个参数的和。