#include <iostream>
void convertTemperature(double tempIn, char typeIn);
void convertTemperature(int tempInInt, 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)
{
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\n";
}
std::cout << "请输入任何字符结束!" << "\n";
std::cin.get();
}
void convertTemperature(int tempIn, char typeIn)
{
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\n";
}
std::cout << "请输入任何字符结束!" << "\n";
std::cin.get();
}
这个例子,我们可以体验到:对函数进行重载,事实上可以简化编程工作和提高代码的可读性、
事实上,重载不是一个真正的面向对象特征,它只是可以简化编程工作的一种方案,而简化工作正是C++语言的全部追求。
有以下几点需要注意:
1. 对函数(方法)进行重载一点要谨慎,不要“无的放矢”或“乱点鸳鸯”;
2. 要知道重载函数越多,该程序就越不容易看懂;
3. 注意区分重载和覆盖(覆盖现在还没学到);
4. 我们只能通过不同参数进行重载,但不能通过不同的返回值(尽管后者也是一种区别);
5. 最后,对函数进行重载的目的是为了方便对不同数据类型进行同样的处理。