C++核心_3函数提高

3.1函数默认参数

c++中,函数形参可以有默认值。

返回值类型  函数名  (参数 = 默认值)
{
}
# include<iostream>
using namespace std;
// 函数的默认参数
int func(int a, int b=10, int c=20) // 1、如果某个位置已经有了参数,那么从这个位置往后 从左到右都必须有默认值。
{
	return a + b + c;
}
// 2、如果函数声明有默认参数,函数实现就不能有默认参数。
int func2(int a=10, int b=20);

int main() {
	cout<<func(1, 2)<<endl; // 传值了用传的值,没传用默认值。
	cout << func2() << endl;
	system("pause");
	return 0;
}
// 2、如果函数声明有默认参数,函数实现就不能有默认参数。
int func2(int a, int b)
{
	return a + b;
}

3.2函数占位参数

# include<iostream>
using namespace std;
// 占位参数
// 返回值类型 函数名(数据结构){}
// 占位参数也可以有默认参数
void func(int a, int)
{
	cout << "asd" << endl;
}
void func2(int a, int = 10)
{
	cout << "asd" << endl;
}
int main() {
	func(10, 10); // 要传对应的数据
	system("pause");
	return 0;
}

3.3函数重载

3.3.1函数重载概述

作用:函数名可以相同,提高复用性。
条件: 同一作用域下,函数名相同,函数参数类型不同、个数不同、顺序不同
函数的返回值不可以作为重载条件

# include<iostream>
using namespace std;
// 函数重载
void func()
{
	cout << "函数重载" << endl;
}
void func(int a)
{
	cout << "func(int a)函数重载" << endl;
}
void func(double a)
{
	cout << "func(double a)函数重载" << endl;
}
int main() {
	func();
	func(1);
	func(3.1415);
	system("pause");
	return 0;
}

3.3.2函数重载注意事项

引用作为重载条件
函数重载碰到函数默认参数

# include<iostream>
using namespace std;
// 函数重载 注意事项
//引用作为重载条件
void fun(int &a)
{
	cout << "fun(int &a)" << endl;
}
void fun(const int& a)
{
	cout << "fun(const int& a)" << endl;
}
//函数重载碰到函数默认参数
void fun2(int a,int b=10)
{
	cout << "fun2(int a,int b)" << endl;
}
void fun2(int a)
{
	cout << "fun2(int a)" << endl;
}

int main() {
	int a = 10;
	fun(a); // int &a = 10;不合法
	fun(10); // const int &a=10; 合法(临时数据 指向 临时空间)

	fun2(10); //函数重载 碰到 默认参数,出现二义性 报错,尽量避免这种情况
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值