您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
第6讲-函数的重载
发布时间:2021-05-11 22:04:14编辑:雪饮阅读()
所谓的函数的重载,一般典型的都是对于相同的函数,不同的函数类型的定义。
那么这里将上篇中华氏度与摄氏度进行转换的程序,我们来通过函数重载的方式来实现下。
其具体实例如:
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
void converTemperature(double num,string t,int type){
if(type==1){
cout << "华氏度:" << num * 9 / 5 + 32 << "F" << endl;
}
else if(type==2){
cout << "摄氏度:" << (num - 32) * 5 / 9 << "C" << endl;
}
else{
cout<<"输入有误!";
}
cout<<"\n";
}
void converTemperature(int num,string t,int type){
if(type==1){
cout << "华氏度:" << num * 9 / 5 + 32 << "F" << endl;
}
else if(type==2){
cout << "摄氏度:" << (num - 32) * 5 / 9 << "C" << endl;
}
else{
cout<<"输入有误!";
}
cout<<"\n";
}
int main()
{
string t;
cout << "请输入带有符号的温度值(123C / 100C):";
cin >> t;
cout << "输入的带有符号的温度值为:" << t << endl;
if (t.find('c', 0) != -1 || t.find('C', 0) != -1)
{
int index_c=t.find('c', 0);
if(index_c==-1){
index_c=t.find('C', 0);
}
double num = stod(t.substr(0,index_c));
converTemperature(num,t,1);
}
else if (t.find('f', 0) != -1 || t.find('F', 0) != -1)
{
int index_f=t.find('f', 0);
if(index_f==-1){
index_f=t.find('F', 0);
}
double num = stod(t.substr(0, index_f));
converTemperature(num,t,2);
}
else
{
converTemperature(0,t,1);
}
//下面是int形式
if (t.find('c', 0) != -1 || t.find('C', 0) != -1)
{
int index_c=t.find('c', 0);
if(index_c==-1){
index_c=t.find('C', 0);
}
int num = stod(t.substr(0,index_c));
converTemperature(num,t,1);
}
else if (t.find('f', 0) != -1 || t.find('F', 0) != -1)
{
int index_f=t.find('f', 0);
if(index_f==-1){
index_f=t.find('F', 0);
}
int num = stod(t.substr(0, index_f));
converTemperature(num,t,2);
}
else
{
converTemperature(0,t,1);
}
return 0;
}
那么编译并运行效果如:
关键字词:c++,函数,函数重载
上一篇:第五讲 输出输入小结
下一篇:第七讲 复杂的数据类型