C++中的函数重载

C++函数重载

函数重载是指函数名在满足一定的条件下可以相同,这样做的作用是能够提高代码的复用性,同一个函数名在不同的条件下可以有不同的功能。

须满足的条件:

  • 函数位于同一个作用域下
  • 函数名称相同
  • 函数参数类型不同或者个数不同或者顺序不同

案例一:参数个数不同

#include<iostream>
using namespace std;

void func()		//函数中参数个数为0
{
	cout << "函数1" << endl;
}
void func(int a)	//函数中参数个数为1
{
	cout << "函数2" << endl;
}
int main()
{

	int a = 5;
	func();
	func(a);

	system("pause");

	return 0;
}

结果:两次调用的函数名虽然相同,但是由于参数的个数不同,调用到了不同的函数。

案例二:参数类型不同

#include<iostream>
using namespace std;

void func(int a)	//参数的数据类型是整型
{
	cout << "函数1" << endl;
}
void func(float a)	//参数的数据类型是浮点型
{
	cout << "函数2" << endl;
}
int main()
{

	int a = 5;
	float b = 5.5;

	func(a);
	func(b);

	system("pause");

	return 0;
}

结果:两次调用的函数名虽然相同,但是由于参数的数据类型不同,调用到了不同的函数。
案例三:参数顺序不同

#include<iostream>
using namespace std;

void func(int a,float b)	//整型在前,浮点型在后
{
	cout << "函数1" << endl;
}
void func(float a,int b)	//浮点型在前,整型在后
{
	cout << "函数2" << endl;
}
int main()
{

	int a = 5;
	float b = 5.5;

	func(a,b);
	func(b,a);

	system("pause");

	return 0;
}

结果:两次调用的函数名虽然相同,但是由于参数的顺序不同,调用到了不同的函数。

注意事项
函数的返回值不可以作为函数重载的条件

int func()	//函数的返回值类型为整型
{
	cout << "函数1" << endl;
}
float func()	//函数的返回值类型为浮点型
{
	cout << "函数2" << endl;
}

这样的两个函数不能构成重载,运行时编译器会报错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值