一般来说呢,函数在调用的时候,形参从实参那里取得值。当我们多次调用用一函数同一实参的时侯,C++就给出了更简单的处理办法。给形参以默认值,这样就不用从实参那里取值了。
默认参数规则:
只有参数列表后面部分的参数才可以提供默认参数值,一旦在一个函数调用中开始使用默认参数值,那么这个参数后的所有参数都必须使用默认参数值。
单个默认参数
#include<iostream>
using namespace std;
void test( int num = 3)
{
cout << num << endl;
}
void main()
{
test(5);//这个不填参数的时候,会使用你的默认参数,填参数时,使用你填的
}
多个默认参数
#include<iostream>
using namespace std;
//如果默认参数出现,那么右边的都必须有默认参数
int volume(int x, int y= 2, int z= 3)
{
return x * y * z;
}
void main()
{
int a = volume(5);
int b = volume(5,5);
int c = volume(5,5,5);
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
运行结果如下:
占位参数:只有在参数类型声明,而没有参数名声明,一般情况下,在函数体内部无法使用占位参数的
#include<iostream>
using namespace std;
int test(int x, int y, int )
{
return x*y;
}
void main()
{
//int a(5,6)//不把最后一个占位参数补上的话是会报错的
int a = test(5,6,7);
cout << a << endl;
}
默认参数是可以和占位参数一起使用的:
#include<iostream>
using namespace std;
int test(int x, int y=5, int=0 )
{
return x*y;
}
void main()
{
int b = test(5);
int a = test(5,6);
cout << b << endl;
cout << a << endl;
}
默认参数和占位参数在一起,都能调用起来。
C++可以声明占位符参数,占位符参数一般⽤用于程序扩展和对C代码的兼容 。