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语言不支持缺省参数

猜你喜欢

转载自blog.csdn.net/m0_38121874/article/details/81165949