你可以在函数中为一个或多个值调用参数指定默认参数。假如相应的参数被省略,那该参数会用默认参数来取代。
使用时应注意以下几点:
1. 默认参数应该只在函数的引用性声明中给出,不应在函数定义性声明中重复定义。
2. 你可能定义了超过一个的默认参数,但所有的默认参数位置必须是在最右边。所以省略参数时,也是从最右边开始的。
3. 默认参数只能被用在值传递的函数中。
例如:
#include <iostream>
using namespace std;
void showVolume(int length, int width=1, int height=1);
int main()
{
showVolume(4, 6, 2);
showVolume(4,6);
showVolume(4);
return 0;
}
void showVolume(int length, int width, int height)
{
cout << "Volume of a box with/n"
<< "Length=" <<length <<",Width="<<width<<endl
<<"and Heigh=" <<height <<" is " <<length * width*height <<endl;
}