缺省参数

缺省参数
在C语言中,函数没有指定参数列表时,默认可以接收任意多个参数;
在C++中,因为有严格的参数类型检测,所以,函数没有参数列表时,默认为void,不接收任何参数。
以下是例子:

C++中:
#include<iostream>
using namespace std;

void Test()
{}

int main()
{
    Test(10);
    Test(10, "hello world");
    return 0;
}

结果:

这里写图片描述

C语言:
#include<stdlib.h>

void Test()
{}

int main()
{
    Test(10);
    Test(10, "hello world");
    return 0;
}

结果:
这里写图片描述

· 缺省参数概念:
(1)缺省参数是声明或定义函数时为函数的参数指定一个默认值 ;
(2)在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。

#include<iostream>
using namespace std;

void Test(int a = 0)
{
    cout << a << endl;
}

int main()
{
    Test();   //没有传参时,使用参数默认值,则输出结果为0;
    Test(10); //传参时,使用给定的参数,则输出结果为10.

    system("pause");
    return 0;
}

· 缺省参数的分类:
(1)全缺省参数:函数的每个参数都有缺省值,传参时,可传任意多个参数,且参数的传参是从左依次往右进行;

#include<iostream>
using namespace std;

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

int main()
{
    Test();
    Test(10);
    Test(10, 20);
    Test(10, 20, 30);
    return 0;
}

结果如下:
这里写图片描述
(2)半缺省参数:函数的部分参数有缺省值,且缺省值要从右往左依次给

#include<iostream>
using namespace std;

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

int main()
{
    //Test();   //编译时会出错,因为a没有缺省值,所以必须传参。
    Test(10);
    Test(10, 20);
    Test(10, 20, 30);
    return 0;
}

结果:
这里写图片描述
注意:
· 带缺省值的参数必须放在参数列表的最后面;
· 缺省参数不能同时在函数声明和定义中出现,只能在其中一个出现;
· 缺省值必须是常量或者全局变量;
· C语言不支持。

  • 17
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值