目录
1--默认参数的使用
① 函数某个参数有默认值,则此参数往后的参数都应设置默认值;
int test1(int a = 1, int b, int c); // ×
int test1(int a, int b = 1, int c = 2); // √
② 函数声明和函数实现不能同时设置参数默认值;
// 错误用法:定义和实现都设置参数值
int test2(int a = 1, int b = 2);
int test2(int a = 1, int b = 2){
return a + b;
}
// 正确用法:
int test2(int a = 1, int b = 2);
int test2(int a, int b){
return a + b;
}
// 正确用法:
int test2(int a, int b);
int test2(int a = 1, int b = 2){
return a + b;
}
2--函数占位参数
① 占位参数可以用默认值
int func(int a = 10, int = 20);
int = 20 就是为占位参数设置默认值,占位参数用数据类型来指定,不需要使用具体的变量名;
3--函数重载
① 作用:函数名可以相同,提高复用性;
② 重载条件:在同一个作用域下,函数名称相同,函数参数类型、参数个数或参数顺序不同;函数的返回值不可以作为函数重载的条件;
#include <iostream>
void func(){
std::cout << "func() calling .." << std::endl;
}
void func(int a){
std::cout << "func(int a) calling .." << std::endl;
}
void func(double a){
std::cout << "func(double a) calling .." << std::endl;
}
void func(int a, double b){
std::cout << "func(int a, double b) calling .." << std::endl;
}
void func(double b, int a){
std::cout << "func(double b, int a) calling .." << std::endl;
}
int main(){
func();
int a = 10;
func(a);
double b = 10;
func(b);
func(a, b);
func(b, a);
return 0;
}
③ 引用作为重载
#include <iostream>
void func(int &a){
std::cout << "func(int &a) calling .." << std::endl;
}
void func(const int &a){
std::cout << "func(const int &a) calling .." << std::endl;
}
// int 和 const int类型不同,满足重载的条件
int main(){
func(10);
// int &a = 10 不合法
// const int &a = 10 合法
// 因此调用的是func(const int &a)
return 0;
}
④ 函数重载与默认参数的冲突
#include <iostream>
void func(int a){
std::cout << "func(int a) calling .." << std::endl;
}
void func(int a, int b = 10){
std::cout << "func(int a, int b = 10) calling .." << std::endl;
}
int main(){
func(10);
return 0;
}
上面的代码是错误的,出现二义性,因为 func(10) 可以调用两个函数;