C++函数重载 overloading

//函数重载 overloading  封装 
//实质:用同样的名字
//再定义一个有着不同参数
//但有着同样用途的函数 

//目的:方便对不同数据类型进行同样的处理 


//不同:可以是参数个数上面的不同
//		也可以是参数数据类型的不同

//编写一个“温度单位转换程序”
//提示用户 以 [xx.x C] 或 [xx.x F]的格式输入
//要求:输入:34.2 C自动转换为90.32 F并输出 
#include <iostream>

using namespace std;

void convertTemperature(double tempIn,char typeIn);
void convertTemperature(int tempIn,char typeIn);
int main()
{
    
    

	 
	 double tempIn;
	 int tempInInt;
	 char  typeIn;
	 
	 cout<<"请 以 [xx.x C] 或 [xx.x F]的格式输入一个温度:";
	 cin>>tempIn>>typeIn;
	 cin.ignore(100,'\n');
	 cout<<"\n";

	convertTemperature(tempIn,typeIn);
	
	cout<<"请 以 [xx C] 或 [xx F]的格式输入一个温度:";
	cin>>tempInInt>>typeIn;
	cin.ignore(100,'\n');
	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')
	 {
    
    
	 	cout<<tempIn<<typeIn<<" = "
		<<tempOut<<typeOut<<"\n\n";
	 }
	 else
	 	cout<<"输入错误!,请输入任意字符结束程序"<<"\n\n";
	 	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<<"\n\n";
	 }
	 else
	 	cout<<"输入错误!,请输入任意字符结束程序"<<"\n\n";
	 	cin.get(); 
}

//注:
//对函数(方法)进行重载一定要谨慎。不要 无的放矢  乱点鸳鸯 

//重载函数越多,该程序矩矱不容易看懂 

//注意区分重载和覆盖

// 只能通过不同参数进行重载,
//但不能通过不同的返回值


猜你喜欢

转载自blog.csdn.net/qq_48167493/article/details/120596582