🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# C++ 函数中的默认参数 > 原文: [https://beginnersbook.com/2017/08/cpp-default-arguments/](https://beginnersbook.com/2017/08/cpp-default-arguments/) 在调用函数时不提供任何参数或仅提供少量参数时,将使用默认参数。在编译程序期间使用默认参数。例如,假设您有一个[用户定义的函数](https://beginnersbook.com/2017/08/cpp-functions/)`sum`声明如下:`int sum(int a=10, int b=20)`,现在在调用此函数时,您不提供任何参数,简称为`sum()`;那么在这种情况下结果将是 30,编译器使用函数签名中声明的默认值 10 和 20。如果你只传递一个这样的参数:`sum(80)`那么结果将是 100,使用传递的参数 80 作为第一个值,20 个从默认参数中获取。 ## 示例:C++ 中的默认参数 ```cpp #include <iostream> using namespace std; int sum(int a, int b=10, int c=20); int main(){ /* In this case a value is passed as * 1 and b and c values are taken from * default arguments. */ cout<<sum(1)<<endl; /* In this case a value is passed as * 1 and b value as 2, value of c values is * taken from default arguments. */ cout<<sum(1, 2)<<endl; /* In this case all the three values are * passed during function call, hence no * default arguments have been used. */ cout<<sum(1, 2, 3)<<endl; return 0; } int sum(int a, int b, int c){ int z; z = a+b+c; return z; } ``` **输出:** ```cpp 31 23 6 ``` ## 默认参数的规则 正如您在上面的示例中所看到的,我在函数声明期间仅为两个参数`b`和`c`分配了默认值。您可以为所有参数或仅选定的参数指定默认值,但在仅为某些参数指定默认值时,请记住以下规则: > **如果为参数指定默认值,则必须为后续参数分配默认值,否则将出现编译错误。** **例如:**让我们看一些有效和无效的案例。 **有效:**以下函数声明有效: ```cpp int sum(int a=10, int b=20, int c=30); int sum(int a, int b=20, int c=30); int sum(int a, int b, int c=30); ``` **无效:**以下函数声明无效: ```cpp /* Since a has default value assigned, all the * arguments after a (in this case b and c) must have * default values assigned */ int sum(int a=10, int b, int c=30); /* Since b has default value assigned, all the * arguments after b (in this case c) must have * default values assigned */ int sum(int a, int b=20, int c); /* Since a has default value assigned, all the * arguments after a (in this case b and c) must have * default values assigned, b has default value but * c doesn't have, thats why this is also invalid */ int sum(int a=10, int b=20, int c); ```