目录
一.什么是缺省参数
#include<iostream>
using namespace std;
void Func(int a = 1)
{
cout << a << endl;
}
int main(void)
{
Func();
Func(2);
return 0;
}
Func函数的形参int a = 1 这就是给形参一个缺省值,当没有实参传入的时候,函数会使用这个默认值 ,如果传参了那么就使用传入的。
二.缺省参数的分类
1.全缺省
void Func(int a = 10, int b = 20, int c = 30)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
2.半缺省
void Func(int a, int b = 10, int c = 20)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
注意:
1. 半缺省参数必须从右往左依次
来给出,不能间隔着给
2. 缺省参数不能在函数声明和定义中同时出现
//a.h
void Func(int a = 10);
// a.cpp
void Func(int a = 20)
{}
// 注意:如果声明与定义位置同时出现,恰巧两个位置提供的值不同,那编译器就无法确定到底该用那
个缺省值。
3. 缺省值必须是常量或者全局变量
4. C语言不支持(编译器不支持)
函数声明和定义不可以同时给缺省参数,如果同时给了就会发生默认参数重定义的情况。因为怕两个地方的缺省值不同,一般都是在函数的声明处给缺省参数。