1 函数重载
作用:函数名可以相同,提高复用性
函数重载满足条件:
- 在同一个作用域下
- 函数名称相同
- 函数参数类型不同 或者 个数不同 或者 顺序不同
注意:函数的返回值不可以作为函数重载的条件
//1 必须在同一个作用域下
//2 函数名称相同
//3 函数参数 类型不同 或者 个数不同 或者 顺序不同
void func() {
cout << "01" << endl;
}
void func(int a) {
cout << "02" << endl;
}
void func(double a) {
cout << "03" << endl;
}
void func(int a,double b) {
cout << "04" << endl;
}
void func(double b, int a) {
cout << "05" << endl;
}
// 注意:函数的返回值不可以作为函数重载的条件
void func(double b, int a) {
cout << "05" << endl;
}
int func(double b, int a) {//错误
cout << "05" << endl;
}
注意事项:
1 引用作为重载条件
void fun(int& a) {//当直接传10时,int &a = 10;不合法
cout << "01" << endl;
}
void fun(const int& a) {// const int &a = 10;合法,因为加上const时,编译器自动给10创建临时变量
cout << "02" << endl;
}
int main() {
int a = 10;
fun(a);//01
fun(10);//02
system("pause");
return 0;
}
2 函数重载碰到函数默认参数
//2 函数重载碰到函数默认参数
void fun1(int a,int b = 10 ) {
cout << "01" << endl;
}
void fun1(int a) {
cout << "02" << endl;
}
int main() {
fun1(10);//既能01也能02,函数重载碰到默认参数会出现二义性,尽量避免这种
fun1(10,20);//正确
system("pause");
return 0;
}