函数的缺省参数范例
#include <iostream>
using namespace std;
/*
函数的参数指定为默认值称缺省参数
*/
double Area(double Width, double Length = 12.0);
//默认值只能在函数声明时指定,或者函数定义放在声明位置
/*不可以同时在函数声明和定义式指定*/
int main()
{
double A;
A = Area(6.5);
cout << A << endl;
A = Area(6.5,10);
cout << A << endl;
return 0;
}
double Area(double Width, double Length/* = 12.0 */)
{
return Width*Length;
}
输出:
78
65
*********************************************************
补充:
*********************************************************
eg1.
一个函数声明:
void Func(float, float x = 0, int n = 5, char = 'r');
正确调用:
Func(1.5);
Func(3.2, 1.0);
Func(0.0, 1.0, 10, 'a');
错误的调用:
Func(1.0, 2.0, 'a');
eg2.
函数重载和缺省值同时使用时,不能只以参数的数量来区别,如下:
int Func(int n, int m = 0, float x = 1.0);
int Func(int n, int m);
下面的调用将引起歧义,编译出错M = Func(2, 3);