当前位置: 首页 > 文档资料 > C++大学教程 >

3.18 默认参数

优质
小牛编辑
131浏览
2023-12-01

函数调用可能通常传递参数的特定值。程序员可以将该参数指定为默认参数,程序员可以提供这个参数的默认值。当函数调用中省略默认参数时,默认参数值自动传递给被调用函数。

默认参数必须是函数参数表中最右边(尾部)的参数。调用具有两个或多个默认参数的函数时,如果省略的参数不是参数表中最右边的参数,则该参数右边的所有参数也应省略。默认参数应在函数名第一次出现时指定,通常是在函数原型中。默认值可以是常量、全局变量或函数调用。默认参数也可以用于内联函数中。

图3.23演示用默认参数计算箱子的容积。第5行 boxVolume 的函数原型指定所有三个参数的默认值均为1。注意,默认值只能在函数原型中定义,另外,我们在函数原型中提供变量名以增加可读性,当然变量名在函数原型中不是必需的。

// Fig. 3.23:fig03 23.cpp
// Using default arguments
#include <iostream.h>
int boxVolume( int length = 1, int width = 1, int height = 1 );
int main(){
cout << "The default box volume is: "<< boxVolume( )
<< "\n\mThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: "<< boxVolume( 10 )
<< "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height i is: "<< boxVolume( 10, 5 )
<< "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 2 is: "<< boxVolume( 10, 5, 2 )
<< endl;
}
// Calculate the volume of a box
iht boxVolume{int length, iht width, int height){
return length * width * height;
}

输出结果:

The default box volume is: 1

The volume of a box with length 10,
width 1 and height 1 is: 10

The volume of a box with length 10,
width 5 and height 1 is: 50

The volume of a box with length 10,
width 5 and height 2 is: 100

图3.23 用默认参数计算箱子的容积

首次调用函数 boxvolume(第9行)时不指定参数,因此三个参数都用默认值。第二次调用函数boxVolume(第11行)时只传递length参数,因此width和height参数用默认值。第三次调用函数boxVolume(第13行)时只传递length和width参数,因此height参数用默认值。最后一次调用函数boxVolume(第15行)时传递length、width和height参数,因此不用默认值。

编程技巧3.13

使用默认值能简化函数调用,但有些程序员认为显式指定所有参数更清楚。

常见编程错误3.31

指定和试图使用的默认参数不是最右边的参数(即没有把该参数右边的参数指定为默认参数)。