写在前面:作为一只小白,感谢小甲鱼老师提供这么好的入门课程。因此在这里做个笔记,如有侵权请联系删除。
www.fishc.com
① 函数重载概念
C++里的函数重载(overloading)机制比我们此前见到的东西很高深,这种语言的灵活性和强大功能在它身上体现得淋漓尽致。
所谓函数重载的实质就是用同样的名字再定义一个有这不同参数但有着同样用途的函数。(人格分裂,多重身份......)
#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();
}
这个例子,我们可以体验到:对函数进行重载,事实上可以简化编程工作和提高代码可读性。
大家想必已经体会到重载的优越性了,事实上,重载不是一个真正的面向对象特征,它只是可以简化编程工作的一种方案,而简化工作正式C++语言的全部追求。
有以下几点需要大家注意的:
对函数(方法)进行重载一定要谨慎,不要“无的放矢”或者“乱点鸳鸯”;
要知道函数重载越多,该程序就越不容易看懂;
注意区分重载和覆盖(覆盖后面我们会讲到)
我们只能通过不同参数进行重载,但不能通过不同的返回值(尽管后者也是一个区别);
最后,对函数精选重载的目的是为了方便对不同数据类型进行同样的处理。