重载不是面对对象的特征,只是可以简化处理。 同一个函数实现不同功能。 重载要谨慎,过多不易使程序读懂。
只能通过不同参数重载,不能通过不同返回值。重载:参数不同。覆盖:全都相同
//重载不是面对对象的特征,只是可以简化处理。 同一个函数实现不同功能。 重载要谨慎,过多不易使程序读懂。
//只能通过不同参数重载,不能通过不同返回值。重载:参数不同。覆盖:全都相同
#include <iostream>
void convertTemperature(double tenmIn,char typeIn);
void convertTemperature(int tenmIn,char typeIn);
int main()
{
double tempIn;
int tempInInt;
char typeIn;
std::cout <<"输入格式[xx.x C] [xx.x F]";
std::cin >> tempIn >> typeIn;
std::cin.ignore(100,'\n');
std::cout <<"\n";
convertTemperature(tempIn, typeIn);
std::cout <<"输入格式[xx C] [xx F]";
std::cin >> tempInInt >> typeIn;
std::cin.ignore(100,'\n');
std::cout <<"\n";
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;
double 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')
{
std::cout <<tempIn << typeIn<<"="<< tempOut << typeOut << "\n\n";
}
else
{
std::cout << "输入错误" <<"\n";
}
std::cout << "请输入任何字符结束程序" <<"\n\n";
std::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')
{
std::cout <<tempIn << typeIn<<"="<< tempOut << typeOut << "\n\n";
}
else
{
std::cout << "输入错误" <<"\n";
}
std::cout << "请输入任何字符结束程序" <<"\n\n";
std::cin.get();
}