小甲鱼-C++快速入门笔记(6)之函数的重载

定义:用同样的名字再定义一个有着不同参数但有着同样用途的函数,可以是参数个数上的不同,也可以是参数数据类型上的不同

#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();
}

课后作业:

1、为什么不能通过返回值不同来重载函数(方法)?

C++调用一个函数是可以忽略其返回值的,这种情况下编译器就无法根据返回值类型来确定调用哪一个函数。所以,重载不能用返回值类型来区别。

2、利用重载函数的方法设计一个程序,该程序通过函数“calc()”进行计算并返回显示结果。

---当传入一个参数时,计算该参数的平方值

---当传入两个参数时,计算两个参数的积

---当传入三个参数时,计算三个参数的和。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值