当前视点!菜狗小提米的技美学习笔记(230202-C++:函数重载)
//函数重载
(资料图片仅供参考)
// 可以让函数名称相同,提高复用性
//函数重载的条件:
//同一个作用域下;函数名相同;函数的参数类型、个数、顺序不同
void f_0() {
cout << "f_0 is working" << endl;
}
//函数参数个数不同,形成重载
void f_0(bool a) {
cout << "f_0(BOOL) is working" << endl;
}
//函数参数类型不同,形成重载
void f_0(int a) {
cout << "f_0(INT) is working" << endl;
}
//函数参数顺序不同,形成重载
void f_0(int a, bool b) {
cout << "f_0(INT/BOOL) is working" << endl;
}
void f_0(bool a, int b) {
cout << "f_0(BOOL/INT) is working" << endl;
}
//注意事项:引用作为重载条件时
void f_1(int& a) {//传入变量
cout << "f_1(&) is working" << endl;
}
void f_1(const int& a) {//传入常量
cout << "f_1(const &) is working" << endl;
}
//函数重载最好不要使用函数默认值
//错误案例:
//void f_2(int a , int b = 10) {
//}
int main() {
f_0();
f_0(true);
f_0(20);
f_0(10, true);
f_0(false, 10);
cout << endl;
int a = 100;
f_1(a);//传入变量,数据存储在栈区,走f_1(&)
f_1(15);//传入常量15,数据存储在常量/静态区,走f_1(const &)
cout << endl;
system("pause");
return 0;
}