【C++】缺省参数

1、概念

缺省参数是指在声明或定义函数时,为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。

2、缺省参数分类

2.1 全缺省参数

全缺省参数,即函数的全部形参都设置为缺省参数。

void Print(int a = 10, int b = 20, int c = 30)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}

2.2 半缺省参数

半缺省参数,即函数的参数不全为缺省参数。

void Print(int a, int b, int c = 30)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}

注意:
1、半缺省参数必须从右往左依次给出,不能间隔着给。

2、缺省参数不能在函数声明和定义中同时出现
缺省参数只能在函数声明时出现,或者函数定义时出现(二者之一均正确)。

3、缺省值必须是常量或者全局变量。

//正确示例
int x = 30;//全局变量
void Print(int a, int b = 20, int c = x)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}
posted @ 2024-07-31 07:18  NotReferenced  阅读(9)  评论(0编辑  收藏  举报