函数的重载实例
2019-03-11 16:20
471 查看
[code]#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. 最后,对函数进行重载的目的是为了方便对不同数据类型进行同样的处理。
相关文章推荐
- 以复数运算为实例的类实现、函数重载、模板类操作
- php protected只能被继承,不可以在实例中调用,parent::调用父类(子类函数的重载对父类的函数没有影响)
- Python函数重载实例
- 关于《VC++权威剖析:MFC的原理、机制与开发实例》中的函数重载
- PHP利用func_get_args和func_num_args函数实现函数重载实例
- java 函数的重载和重写实例代码
- PHP利用func_get_args和func_num_args函数实现函数重载实例
- Python基类函数的重载与调用实例分析
- Python基类函数的重载与调用实例分析
- PowerShell函数实现类似重载功能实例
- 操作符函数及重载(4)
- js函数排序的实例代码
- 通过实例讲解来学习ASP中的函数
- matlab 画图函数的实例
- 函数模版、重载和特化的匹配规则
- 函数的重载、覆盖和隐藏
- C/C++语法[01]---C++默认参数与函数重载 注意事项
- 类成员函数的重载、覆盖和隐藏区别
- C#自定义字符串补0函数实例