【C++】缺省参数及其分类

C++中有个重要的概念叫做缺省参数。那么什么是缺省参数呢?我们可以把它理解为备胎。

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

void TestFunc(int a = 0)
{
    cout<<a<<endl;
}
int main()
{
   TestFunc(); // 没有传参时,使用参数的默认值
   TestFunc(10); // 传参时,使用指定的实参
}

它主要有以下两种形式:

1.全缺省参数

在声明和定义时,所有参数都指定了默认值叫做全缺省参数。

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

2.半缺省参数

在声明和定义时,部分参数指定了默认值叫做半缺省参数。

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

或者

void TestFunc(int a, int b , int c = 20)
{
   cout<<"a = "<<a<<endl;
   cout<<"b = "<<b<<endl;
   cout<<"c = "<<c<<endl;
}

像这样是错误的。因为这样的话如果传两个参数,系统搞不懂你是传给前两个还是后两个,难以明确。所以缺省参数必须连续并且从右往左缺省。 

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

 注意:

1. 半缺省参数必须从右往左依次来给出,不能间隔着给。

2. 缺省参数不能在函数声明和定义中同时出现。

//a.h
void TestFunc(int a = 10);
// a.c
void TestFunc(int a = 20)
{}
// 注意:如果声明与定义位置同时出现,恰巧两个位置提供的值不同,那编译器就无法确定到底该用那个
缺省值。

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

4. C语言不支持(编译器不支持)

 

猜你喜欢

转载自blog.csdn.net/Miss_Monster/article/details/84725273