函数参数的默认值本篇介绍函数参数的默认值在之前我们讲解的函数声明时都是按如下方式声明的如void Func1int A{cout A endl;}void Func2string str{cout str endl;}在上面两个函数中我们都定义了形参而参数默认值就是为其中的形参赋值这个很像正常为变量赋值如 Func1 我可以这样声明void Func1int A 10{cout A endl;}Func2 我可以改为void Func2string str hello world{cout str endl;}像上面这样就是在为函数参数赋值也就是默认值通常管这类参数也叫做可选参数。在这种情况下我们调用函数时可以不传入任何数据在不传入任何数据时函数会使用给定的默认值。代码讲解一下更清晰以Func2为例#include iostreamusing namespace std;void Func2string str hello world{cout str endl;} // 我们声明并定义了一个输出字符串的函数其中形参有默认值即hello worldint main(){Func2();// 按之前学习的内容括号内应该传入string类型的变量或字符串但此处没有// 这就意味着该函数会使用参数默认值了代码运行会输出hello worldstring str HELLO WORLD;Func2 (str);//此时再次调用Func2函数并传入了str变量则原有的参数默认值被覆盖取而代之的是//HELLO WORLD}输出hello worldHELLO WORLD这就是参数默认值的第一个使用规则默认值支持多个且类型无须一致如void Func3int A 10string str “hello”bool b false{cout A A endl;cout str str endl;cout b b endl;}int main(){// 直接调用Func3函数Func3; // 没有传值直接使用默认值Func320“你好世界”true; //传值了原先的默认值被覆盖}输出A10strhellob0A20str你好世界btrue最后如果需要混用即有的参数带默认值有的参数不带默认值那么必须遵守没有默认值的参数放在前面注意看下方参数的内容如void Func3int A string str bool b false{cout A A endl;cout str str endl;cout b b endl;}如果写成void Func3int A 10string str bool b false{cout A A endl;cout str str endl;cout b b endl;}程序就会提示错误。调用的时候将没有默认值的参数赋值即可如Func350“hello”同样也可以赋值覆盖掉默认参数如Func366“WORLD”true输出A50strhellob0A66strWORLDbtrue以上就是函数参数的3个特点。
C++学习笔记系列2-8
函数参数的默认值本篇介绍函数参数的默认值在之前我们讲解的函数声明时都是按如下方式声明的如void Func1int A{cout A endl;}void Func2string str{cout str endl;}在上面两个函数中我们都定义了形参而参数默认值就是为其中的形参赋值这个很像正常为变量赋值如 Func1 我可以这样声明void Func1int A 10{cout A endl;}Func2 我可以改为void Func2string str hello world{cout str endl;}像上面这样就是在为函数参数赋值也就是默认值通常管这类参数也叫做可选参数。在这种情况下我们调用函数时可以不传入任何数据在不传入任何数据时函数会使用给定的默认值。代码讲解一下更清晰以Func2为例#include iostreamusing namespace std;void Func2string str hello world{cout str endl;} // 我们声明并定义了一个输出字符串的函数其中形参有默认值即hello worldint main(){Func2();// 按之前学习的内容括号内应该传入string类型的变量或字符串但此处没有// 这就意味着该函数会使用参数默认值了代码运行会输出hello worldstring str HELLO WORLD;Func2 (str);//此时再次调用Func2函数并传入了str变量则原有的参数默认值被覆盖取而代之的是//HELLO WORLD}输出hello worldHELLO WORLD这就是参数默认值的第一个使用规则默认值支持多个且类型无须一致如void Func3int A 10string str “hello”bool b false{cout A A endl;cout str str endl;cout b b endl;}int main(){// 直接调用Func3函数Func3; // 没有传值直接使用默认值Func320“你好世界”true; //传值了原先的默认值被覆盖}输出A10strhellob0A20str你好世界btrue最后如果需要混用即有的参数带默认值有的参数不带默认值那么必须遵守没有默认值的参数放在前面注意看下方参数的内容如void Func3int A string str bool b false{cout A A endl;cout str str endl;cout b b endl;}如果写成void Func3int A 10string str bool b false{cout A A endl;cout str str endl;cout b b endl;}程序就会提示错误。调用的时候将没有默认值的参数赋值即可如Func350“hello”同样也可以赋值覆盖掉默认参数如Func366“WORLD”true输出A50strhellob0A66strWORLDbtrue以上就是函数参数的3个特点。