1 函数进阶
1.1 函数的默认参数
返回值类型 函数名 (形参 = 默认值){}
如果我们向函数中传入了数据,就使用传入的数据
如果没有传入数据,就使用默认值
#include<iostream>
#include<string>
using namespace std;
int func(int a, int b = 20, int c = 30) {
return a + b * c;
}
int main() {
cout << func(4,0);
return 0;
}
注意: 如果某个参数有默认值,那么这个参数右边的参数也需要有默认值;
//这种是错误的
int func(int a, int b = 20, int c ) {
return a + b * c;
}
注意: 如果函数声明有默认参数,那么函数实现就不写默认参数,声明和实现只能有一处有默认参数
以下是错误的
//声明
int func(int a, int b = 20, int c = 30);
//实现
int func(int a, int b = 20, int c = 30) {
return a + b * c;
}
1.2 函数占位参数
形参列表里可以有占位参数,调用时需要填补该位置
返回类型 函数名(数据类型){}
#include<iostream>
#include<string>
using namespace std;
void func(int) {
cout << "hello world!";
}
int main() {
func(1);
return 0;
}
占位参数也可以有默认参数
1.3 函数重载
1.3.1 函数重载概述
作用:函数名可以相同,提高复用性
函数重载满足条件
- 同一个作用域
- 函数名相同
- 函数参数类型不同或者个数不同或者顺序不同
注意: 返回值不可以作为重载的条件
#include<iostream>
#include<string>
using namespace std;
void func() {
cout << "hello world!";
}
void func(int a) {
cout << "hello world!";
}
int main() {
func();
func(1);
return 0;
}
1.3.2 函数重载注意事项
- 引用作为函数重载的条件
#include<iostream>
#include<string>
using namespace std;
void func(int& a) {
cout << "func(int& a)被调用" << endl;
}
void func(const int& a) {
cout << "func(const int& a)被调用" << endl;
}
int main() {
int a = 10;
func(a);
func(10);//int& a=10;不合法// const int& a=10 he合法
return 0;
}
- 函数重载碰到默认参数
#include<iostream>
#include<string>
using namespace std;
void func(int a) {
cout << "func(int a)" << endl;
}
void func(int a,int b=10) {//有默认参数
cout << "func(int a,int b)" << endl;
}
int main() {
int a = 10;
int b = 20;
//func(a);//这句会报错
func(a,b);
return 0;
}