C++缺省参数

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

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>

using namespace std;

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

int main()
{
    TestFunc();//没有传参时,使用参数的默认值
    TestFunc(10);//传参时,使用指定的实参
    system("pause");
    return 0;
}

运行结果:
这里写图片描述

二、缺省参数分类
1、全缺省参数

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

释:函数的三个参数都赋值了。

2、半缺省参数

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

释:函数的参数没有都赋值。

三、注意事项
1、半缺省参数必须从右往左依次提供,不能间隔地给出。
【例1】error—从左往右给参数赋值

#include<iostream>

using namespace std;

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

int main()
{
    TestFunc();
    return 0;
}

编译结果:
这里写图片描述

【例2】error—间隔地给参数赋值

#include<iostream>

using namespace std;

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

int main()
{
    TestFunc(1, 2, 3);
    return 0;
}

编译结果:
这里写图片描述

2、缺省参数不能同时在函数声明和定义中出现,不能二者择其一。
【例3】error

#include<iostream>

using namespace std;

//函数声明
void TestFunc(int a = 100, int b = 200, int c = 300);

//函数定义
void TestFunc(int a = 10, int b = 20, int c = 30)
{
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
}

int main()
{
    TestFunc();
    system("pause");
    return 0;
}

编译结果:
这里写图片描述

【例4】right—在例3的程序中,把函数定义里的参数去掉

#include<iostream>

using namespace std;

//函数声明
void TestFunc(int a = 100, int b = 200, int c = 300);

//函数定义
void TestFunc(int a, int b, int c)
{
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
}

int main()
{
    TestFunc();
    system("pause");
    return 0;
}

运行结果:
这里写图片描述

3、实参默认从左到右传值
【例5】

#include<iostream>

using namespace std;

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

int main()
{
    TestFunc(1, 2);
    system("pause");
    return 0;
}

运行结果:
这里写图片描述
4、缺省值必须是常量或者全局变量
5、C语言不支持缺省参数

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值