C++:函数高级

1.函数默认参数

//如果我们自己传入数据,就使用自己的数据,如果没有,那么用默认值

//如果某个位置参数有默认值,那么从这个参数往后,必须要有默认值

//如果函数声明有默认值,函数实现的时候就不能有默认参数

#include <iostream>

using namespace std;

int func(int c, int a = 10, int b = 10);

int func(int c, int a, int b)
{
	return c + a + b;
}


int main()
{
	cout << func(20) << endl;
	cout << func(20, 30) << endl;
	cout << func(20, 30, 30) << endl;
	system("pause");
	return 0;
}

2.函数的占位参数

语法:返回类型 函数名 (数据类型){}

#include <iostream>

using namespace std;


void func(int, int, int)
{
	cout << "hello" << endl;
}


int main()
{
	func(1,2,3);
	system("pause");
	return 0;
}

3.函数重载

作用:函数名可以相同,提高复用性

函数重载满足条件:

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

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

#include <iostream>

using namespace std;


void func()
{
	cout << "hello" << endl;
}

int func(int a)
{
	cout << a << endl;
	return 0;
}


int main()
{
	func();
	func(2);
	system("pause");
	return 0;
}

4.函数重载的注意事项

  • 引用作为重载条件
#include <iostream>

using namespace std;


void func(int& a)
{
	cout << "hello" << endl;
}

int func(const int& a)
{
	cout << "world" << endl;
	return 0;
}


int main()
{
	int a = 10;
	const int b = 10;
	func(a);
	func(b);
	func(10);
	system("pause");
	return 0;
}

  • 函数重载碰到默认参数
#include <iostream>

using namespace std;


void func(int a)
{
	cout << "hello" << endl;
}

int func(int a,int b=10)
{
	cout << "world" << endl;
	return 0;
}


int main()
{
	func(10);
	system("pause");
	return 0;
}
//有问题,出现二义性,尽量避免

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值