C++函数重载

函数重载概述

定义:函数重载是指在同一作用域内,可以有一组具有相同函数名,不同参数列表的函数,这组函数被称为重载函数
作用:减少函数名数量,提高复用性

函数重载的条件

1.同一作用域下
2.函数名称相同
3.函数参数类型不同,或者个数不同,或者顺序不同
注意:函数返回值不同不能当做重载条件
示例:

#include<iostream>
using namespace std;
void test()
{
	cout << "1.调用test()" << endl;
}
void test(int a)
{
	cout << "2.调用test(int)" << endl;
}
void test(double a)
{
	cout << "3.调用test(double)" << endl;
}
void test(int a,double b)
{
	cout << "4.调用test(int,double)" << endl;
}
void test(double a, int b)
{
	cout << "5.调用test(double,int)" << endl;
}
int main()
{
	test();//调用无参数的1
	test(1);//调用参数类型为int的2
	test(1.00);//调用参数类型double的3
	test(1, 1.00);// 调用参数类型int,double的4
	test(1.00, 1);// 调用参数类型double,int的5


	return 0;
}

运行结果:
在这里插入图片描述
这五个test函数都处在全局作用域下,所以作用域相同。函数名都为test,所以函数名相同。不同的是参数类型不同(例如test函数2,3),参数个数不同(例如test函数1,2),参数顺序不同(例如test函数4,5)。这就满足了函数重载的条件。

函数重载的注意事项

1.引用作为重载条件

#include<iostream>
using namespace std;
//函数参数类型不同可以发生重载
void test(int &a)
{
	cout << "调用test(int &a)" << endl;//如果传入100,那么等价于int &a=100。但引用必须为合法内存空间(栈区或堆区),而100位于常量区。
}
int test(const int &a)
{
	cout << "调用test(const int &a)" << endl;//当传入100时,const int &a=100;加入const编译器会优化,创建一个临时的数据让a指向它。
}
int main()
{
	int a = 100;
	test(a);//传入a为变量,优先调用无const的函数
	test(100);//常量引用接收常量
	return 0;
}

2.当函数重载有默认函数时

#include<iostream>
using namespace std;
void test(int a,int b=20)//当传入10时,将10赋值给a,b为默认值20.
{
	cout << "调用test(int a,int b=10)" << endl;
}
void test(int a)
{
	cout << "调用test(int a)" << endl;
}
int main()
{
	//test(10);传入为10时,两个函数都能调用,产生二义性,系统报错。
	test(20, 10);//当传入20,10时,将20赋值给a,10赋值给b,调用函数test(int a,int b=20)
	return 0;
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值