缺省参数概念
缺省参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默 认值,否则使用指定的实参。
void fun(int a = 0)
{
cout << a << endl;
}
int main()
{
fun();
fun(10);
system("pause");
return 0;
}
由此可见,C++中支持函数的参数缺省(C不支持),当函数传入参数时,按照传入的值进行运算,没有传入参数时,则按照形参的定义值进行运算。这种功能使函数的功能更加丰富,也大大减少了代码量,但有益必有弊,接着,我们来看一下,参数缺省需要注意些什么:
void fun1(int a = 10,int b=20,int c= 30)//全缺省
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
void fun2(int a = 10 , int b , int c = 30)//半缺省
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
void fun3(int a , int b , int c )//不缺省
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
fun1和fun3都没有问题,只有fun2出现了错误提示,仔细想想:如果中间不缺省,而两边都缺省,那要是我想传入fun2(100,200),那么编译器会怎么解释呢?所以C++就有这样的与法规定:半缺省参数必须从右往左依次来给出,不能间隔着给。 这样就不会出现二义性。
void fun4(int a , int b, int c =10);//声明
void fun4(int a , int b , int c =10 )//定义
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
原来带缺省参数的函数声明和定义一致也会报错
所以,缺省参数不能在函数声明和定义中同时出现。一般情况下,我们在声明时让保持其缺省的状态,定义时,不缺省就可以了。
还要注意两点奥:
1.缺省值必须是常量或者全局变量
2. C语言不支持(编译器不支持)