函数参数的默认值

本篇介绍函数参数的默认值,在之前我们讲解的函数声明时,都是按如下方式声明的,如:

void Func1(int A){

        cout << A <<endl;

}

void Func2(string str){

        cout << str <<endl;

}

在上面两个函数中我们都定义了形参,而参数默认值就是为其中的形参赋值,这个很像正常为变量赋值,如 Func1 我可以这样声明:

void Func1(int A = 10 ){

        cout << A <<endl;

}

Func2 我可以改为:

void Func2(string str = "hello world"){

        cout << str <<endl;

}

像上面这样就是在为函数参数赋值,也就是默认值通常管这类参数也叫做:可选参数在这种情况下,我们调用函数时,可以不传入任何数据,在不传入任何数据时,函数会使用给定的默认值。

代码讲解一下更清晰,以Func2为例:

#include <iostream>

using namespace std;

void Func2(string str = "hello world"){

        cout << str <<endl;

} // 我们声明并定义了一个输出字符串的函数,其中形参有默认值,即:hello world

int main()

{

        Func2();

        // 按之前学习的内容,括号内应该传入string类型的变量,或字符串,但此处没有,

        // 这就意味着,该函数会使用参数默认值了,代码运行会输出:hello world

        string str = "HELLO WORLD";

        Func2 (str);

        // 此时再次调用Func2函数,并传入了str变量,则原有的参数默认值被覆盖,取而代之的是

        // HELLO WORLD

}

输出:hello world

           HELLO WORLD

这就是参数默认值的第一个使用规则;

          默认值支持多个,且类型无须一致,如:

void Func3(int A = 10,string str = “hello”,bool b = false){

        cout << "A:" << A << endl;

        cout << "str:" << str <<endl;

        cout << "b:" << b <<endl;

}    

int main()

{

        // 直接调用Func3函数

        Func3(); // 没有传值,直接使用默认值       

        

        Func3(20,“你好,世界”,true); // 传值了,原先的默认值被覆盖     

}

输出:A:10

           str:hello

            b:0

           A:20

           str:你好,世界

            b:true

最后,如果需要混用,即:有的参数带默认值,有的参数不带默认值,那么必须遵守:没有默认值的参数放在前面,注意看下方参数的内容,如:

void Func3(int A ,string str ,bool b = false){

        cout << "A:" << A << endl;

        cout << "str:" << str <<endl;

        cout << "b:" << b <<endl;

}    

如果写成:

void Func3(int A = 10,string str ,bool b = false){

        cout << "A:" << A << endl;

        cout << "str:" << str <<endl;

        cout << "b:" << b <<endl;

}    

程序就会提示错误。

调用的时候,将没有默认值的参数赋值即可,如:

Func3(50,“hello”);

同样也可以赋值,覆盖掉默认参数,如

Func3(66,“WORLD”,true);

输出:A:50

           str:hello

            b:0

           A:66

           str:WORLD

            b:true

以上就是函数参数的3个特点。

更多推荐