C++中的缺省参数

  1. 缺省参数的作用:

缺省参数是声明或定义函数时为函数的参数指定⼀个缺省值。在调⽤该函数时,如果没有指定实参则采⽤该形参的缺省值,否则使⽤指定的实参,缺省参数分为全缺省和半缺省参数。(有些地⽅把缺省参数也叫默认参数)

     2.缺省参数的分类:

全缺省就是全部形参给缺省值,半缺省就是部分形参给缺省值。

常见的缺省参数的用法:

01

02

03

04

05

06

07

08

09

10

11

12

13

#include <iostream>

 

using namespace std;

void Func(int a = 0)

{

    cout << a << endl;

}

int main()

{

    Func(); // 没有传参时,使⽤参数的默认值

    Func(10); // 传参时,使⽤指定的实参

    return 0;

}

分类如下

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

// 全缺省

void Func1(int a = 10, int b = 20, int c = 30)

{

    cout << "a = " << a << endl;

    cout << "b = " << b << endl;

    cout << "c = " << c << endl << endl;

}

// 半缺省

void Func2(int a, int b = 10, int c = 20)

{

    cout << "a = " << a << endl;

    cout << "b = " << b << endl;

    cout << "c = " << c << endl << endl;

}

int main()

{

    Func1();

    Func1(1);

    Func1(1, 2);

    Func1(1, 2, 3);

    Func2(100);

    Func2(100, 200);

    Func2(100, 200, 300);

    return 0;

}

运行结果如下:

3.缺省参数的注意事项:

当缺省值出现间断赋值或从左往右赋值会出现报错。函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省

值。

错误用例如下:

1

2

3

4

5

6

void Func2(int a = 20, int b = 10, int c )

{

    cout << "a = " << a << endl;

    cout << "b = " << b << endl;

    cout << "c = " << c << endl << endl;

}

函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省值。

用法如下:

01

02

03

04

05

06

07

08

09

10

11

12

// Stack.h

#include <iostream>

#include <assert.h>

using namespace std;

typedef int STDataType;

typedef struct Stack

{

    STDataType* a;

    int top;

    int capacity;

}ST;

void STInit(ST* ps, int n = 4);

01

02

03

04

05

06

07

08

09

10

// Stack.cpp

#include"Stack.h"

// 缺省参数不能声明和定义同时给

void STInit(ST* ps, int n)

{

    assert(ps && n > 0);

    ps->a = (STDataType*)malloc(n * sizeof(STDataType));

    ps->top = 0;

    ps->capacity = n;

}

01

02

03

04

05

06

07

08

09

10

11

// test.cpp

#include"Stack.h"

int main()

{

    ST s1;

    STInit(&s1);

    ST s2;

    STInit(&s2, 1000);

    return 0;

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值