原文: https://www.programiz.com/cpp-programming/default-argument
在本教程中,我们将通过示例学习 C++ 默认参数及其使用。
在 C++ 编程中,我们可以为函数参数提供默认值。
如果在不传递参数的情况下调用具有默认参数的函数,则使用默认参数。
但是,如果在调用函数时传递了参数,则默认参数将被忽略。
默认参数的工作原理

C++ 中的默认参数如何工作
我们可以从上图了解默认参数的工作方式:
调用
temp()时,该函数使用两个默认参数。调用
temp(6)时,第一个参数变为10,而第二个参数使用默认值。调用
temp(6, -2.3)时,两个默认参数都将被覆盖,从而导致i = 6和f = -2.3。传递
temp(3.4)时,该函数的行为异常,因为如果不传递第一个参数,则无法传递第二个参数。
因此,3.4作为第一个参数传递。 由于第一个参数已定义为int,因此实际传递的值为3。
示例:默认参数
#include <iostream>using namespace std;// defining the default argumentsvoid display(char = '*', int = 3);int main() {int count = 5;cout << "No argument passed: ";// *, 3 will be parametersdisplay();cout << "First argument passed: ";// #, 3 will be parametersdisplay('#');cout << "Both arguments passed: ";// $, 5 will be parametersdisplay('$', count);return 0;}void display(char c, int count) {for(int i = 1; i <= count; ++i){cout << c;}cout << endl;}
输出
No argument passed: ***First argument passed: ###Both arguments passed: $$$$$
该程序的工作原理如下:
- 在不传递任何参数的情况下调用
display()。 在这种情况下,display()使用默认参数c = '*'和n = 1。 - 仅使用一个参数调用
display('#')。 在这种情况下,第一个变为'#'。 保留第二个默认参数n = 1。 - 两个参数都调用
display('#', count)。 在这种情况下,不使用默认参数。
我们还可以在函数定义本身中定义默认参数。 下面的程序等同于上面的程序。
#include <iostream>using namespace std;// defining the default argumentsvoid display(char c = '*', int count = 3) {for(int i = 1; i <= count; ++i) {cout << c;}cout << endl;}int main() {int count = 5;cout << "No argument passed: ";// *, 3 will be parametersdisplay();cout << "First argument passed: ";// #, 3 will be parametersdisplay('#');cout << "Both argument passed: ";// $, 5 will be parametersdisplay('$', count);return 0;}
要记住的事情
- 一旦为参数提供默认值,所有后续参数也必须具有默认值。 例如 ```cpp // Invalid void add(int a, int b = 3, int c, int d);
// Invalid void add(int a, int b = 3, int c, int d = 4);
// Valid void add(int a, int c, int b = 3, int d = 4);
2.如果我们在函数定义中定义默认参数而不是函数原型,则必须在函数调用之前定义函数。```cpp// Invalid codeint main() {// function calldisplay();}void display(char c = '*', int count = 5) {// code}
