(C++)函数高级

函数高级

函数默认参数


#include "iostream"
using namespace std;
int func(int a, int b = 20, int c = 30)
{
	return a+b+c;
}
//1.如果某个位置已经有了默认参数,在这个参数之后都必须有默认参数
int func2(int a, int b = 10, int c = 10)
{
	return a+b+c;
}
//b有默认参数,则c也需要有默认参数
//2.如果函数的声明有默认参数,函数实现就不能有默认参数
//声明和实现只能有一个有默认参数
int func3(int a, int b, int c = 10);
int func3(int a, int b, int c)
{
	return a+b+c;
}
//若传入了值,则用传入的,否则用默认值
int main()
{	
	
	system ("pause");
	return 0 ;
}

函数占位参数

int func(int a, int)
{
	cout << "this is func" << endl;
}
//传入参数时需要传入两个参数
//目前阶段用不到占位参数,后面会用到
//占位参数还可以有默认参数

函数重载


#include "iostream"
using namespace std;
/*
函数重载的条件
1.在同一作用下
2.函数名相同
3.函数参数类型不同,或者个数不同,或者顺序不同
*/
int func(double a)
{
	cout << "this is func" << endl;
}
int func(int a)
{
	cout << "this is func chongzai" << endl;
}
int main()
{	
	system ("pause");
	return 0 ;
}

注意事项

1.函数的返回值不可以作为函数重载的条件
2.引用作为重载的条件

#include "iostream"
using namespace std;

void func(int &a)
{
	cout << "this is func" << endl;
}
void func(const int &a)
{
	cout << "this is func chongzai" << endl;
}
int main()
{	
	int a = 2;
	func(a);
	//调用的是形参为int的函数
	func(10);
	//调用的是形参为const int的函数
	system ("pause");
	return 0 ;
}

3.函数重载碰到默认参数

#include "iostream"
using namespace std;

void func(int a, int b = 10)
{
	cout << "this is func" << endl;
}
void func(int a )
{
	cout << "this is func chongzai" << endl;
}
int main()
{	
	func(10);
	//有默认参数和没有默认参数的函数都需要传入一个参数
	//故会报错
	system ("pause");
	return 0 ;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值