C++ 默认参数
在本教程中,我们将在示例的帮助下学习 C++ 默认参数及其工作原理。
在 C++ 编程中,我们可以为函数参数提供默认值。
如果在不传递参数的情况下调用具有默认参数的函数,则使用默认参数。但是,如果在调用函数时传递参数,则会忽略默认参数。
默认参数的工作
我们可以从上图中理解默认参数的工作方式:
-
当
temp()
被调用时,两个参数都是用默认值。 -
当
temp(6)
被调用时,第一个参数为6
,第二个参数使用默认值。 -
当
temp(6, -2.3)
被调用时,两个参数都不使用参数默认值。因此i = 6
并且f = -2.3
。 -
当
temp(3.4)
被传递,则该函数以不期望的方式表现,因为第二个参数不能在不传递第一个参数时使用默认值。因此,
3.4
作为第一个参数传递。由于第一个参数已定义为int
,因此实际传递的值是3
。
示例:默认参数
#include <iostream>
using namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', 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 = '*'
和count = 1
。 - 只用一个参数调用
display('#')
。在这种情况下,第一个变为'#'
。 第二个参数使用默认值count = 3
。 - 用两个参数调用
display('#', count)
。在这种情况下,不使用默认参数。
我们还可以在函数定义本身中定义默认参数。下面的程序与上面的程序等效。
#include <iostream>
using namespace std;
// defining the default arguments
void 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 parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both argument passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
要记住的事情
-
一旦我们为参数提供了默认值,所有后续参数也必须具有默认值。例如,
// 错误的 void add(int a, int b = 3, int c, int d); // 错误的 void add(int a, int b = 3, int c, int d = 4); // 错误的 void add(int a, int c, int b = 3, int d = 4);
-
如果我们在函数定义而不是函数原型中定义默认参数,那么函数必须在函数调用之前定义。
// 错误代码 int main() { // function call display(); } void display(char c = '*', int count = 5) { // code }