目录
一、函数的默认参数
概念:在C++中可以在函数的参数列表中为参数设置默认值
语法:返回值类型 函数名( 参数 = 默认值 ) {}
注意事项:
- 如果某个参数有默认值,那从左往后的参数都必须要有参数值。
int function(int a, int b = 10, int c) {
return a + b + c;
}
- 如果函数的声明有默认值,函数的实现就不能有默认参数。(编译器不知道按哪个运行)
int function(int a, int b = 10, int c = 20);
int function(int a, int b = 10, int c = 20) {
return a + b + c;
}
使用示例:
#include <iostream>
using namespace std;
int function(int a, int b = 10, int c = 20) {
return a + b + c;
}
int main() {
cout << function(1) << endl;//补满未设置初始值的参数
cout << function(1, 2) << endl;//若传入参数则初始值会被替代
system("pause");
return 0;
}
二、占位参数
作用:在形参列表用于占位,当要调用函数时必须要填补该位置。了解即可。
void function(int) {
cout << "123" << endl;
}
三、函数重载
1.基本使用
作用:函数名可以相同,提高复用性
满足条件:
- 同一个作用域下(比如全局作用域)
- 函数名相同
- 函数参数类型不同或个数不同或顺序不同
void function() {
cout << "1" << endl;
}
void function(int a) {
cout << "2" << endl;
}
void function(int a,int b) {
cout << "3" << endl;
}
void function(int b, int a) {
cout << "4" << endl;
}
void function(double a) {
cout << "5" << endl;
}
注意:函数返回值的不同不可作为函数重载的条件。
2.引用作为函数重载的条件
引用作为函数重载有两种方式:
#include <iostream>
using namespace std;
void function(int& a) {
cout << "function(int& a)" << endl;
}
void function(const int& a) {
cout << "function(const int& a)" << endl;
}
int main() {
int a = 10;
function(a);//变量属于可读可写的状态,默认使用第一个
function(10);//使用涉及到常量引用的内容
system("pause");
return 0;
}
3.函数重载碰到默认参数
当加入默认参数时,调用函数系统可能存在不知道调用其中的哪一个参数,如下操作中使用function(a);调用会出错。尽量避免函数重载与默认参数的混合使用。
void function(int a) {
cout << "function(int a)" << endl;
}
void function(int a,int b = 10) {
cout << "function(int a,int b = 10)" << endl;
}