Chapeter09函数提高

1、函数默认参数
如果我们自己传入数据,就用自己的数据,如果没有,那么用默认值
语法:返回值类型 函数名(形参 = 默认值)
注意:
1)如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值

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

2)如果函数声明有默认参数,函数实现就不能有默认参数
PS:函数声明和定义的时候只能赋一次初始默认值

int func2(int a, int b);
int func2(int a = 10, int b = 20)
{
	return a + b;
}

2、函数的占位参数
作用:C++中函数的形参列表可以有占位参数,用来做占位,调用函数时必须填补该位置
语法:返回值类型 函数名(数据类型){ }

void func3(int a, int)
{
	cout << a << endl;
}

3、函数重载
作用:函数名可以相同,提高复用性

函数重载的满足条件:
1)同一个作用域下
2)函数名称相同
3)函数参数 类型不同 或者 个数不同 或者 顺序不同

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

void func4()
{
	cout << "基础函数" << endl;
}

void func4(int a)
{
	cout << "个数不同的调用" << endl;
}

void func4(double a)
{
	cout << "类型不同的调用" << endl;
}

void func4(int a,double b)
{
	cout << "个数不同的调用" << endl;
}

void func4(double a, int b)
{
	cout << "顺序不同的调用" << endl;
}

函数重载的注意事项:
1)引用作为重载函数

void func5(int &a)
{
	cout << "void func5(int &a)调用" << endl;
}

void func5(const int& a)
{
	cout << "void func5(const int& a)调用" << endl;
}

两者属于类型不同

void func5Test()
{
	int a = 10;
	func(a);
	//输出的结果是:void func5(int &a)调用

	func(10);
	//输出的结果是:void func5(const int &a)调用
}

2)函数重载碰到函数默认参数

void func5(int a)
{
	cout << "void func5(int &a)调用" << endl;
}

void func5(int a,int b = 10)
{
	cout << "void func5(const int& a)调用" << endl;
}

PS:此时如果我调用函数:func5(10);
函数重载遇到了默认参数,出现了二义性,就会发生报错

猜你喜欢

转载自blog.csdn.net/qq_43036676/article/details/100738915