一般情况下,函数调用时的实参个数应与形参相同,但为了更方便地使用函数,C++也允许定义具有缺省参数的函数,这种函数调用时,实参个数可以与形参不相同。
定义:定义函数时为形参指定缺省值(默认值)。
- 在调用缺省函数时,对于缺省参数,可以给出实参值,也可以不给,不给则按照默认缺省值使用。
实例:
#includevoid delay(int loops = 5) { //延时函数,默认延时5个时间单位 for (; loops > 0; loops--); } int main() { delay(3); cout<< "延时3个时间单位"<
- 缺省参数的调用:缺省参数不一定是常量表达式,可以是不任意表达式,甚至可以通过函数调用给出。如果缺省实参是任意表达式,则函数每次被调用时该表达式被重新求值。但表达式必须有意义。
- 缺省值可以有多个,但必须在参数列表的右侧,也就是先定义非缺省参数,再定义缺省参数。
实例:
void fun(int a, int b = 23 , int c = 8000) { cout << "a = " << a << " b = " << b << " c = " << c << endl; } int main() { fun(12); fun(10,20); fun(10,20,30); fun(10,,30); // error; return 0; }
- 多文件结构:一般地,缺省参数在公共头文件包含的函数声明中指定,不要函数的定义中指定。如果在函数的定义中指定缺省参数值,在公共头文件包含的函数声明中不能再次指定缺省参数值。缺省实参不一定必须是常量表达式 可以使用任意表达式。
实例:// A.h #ifndef A_H #define A_H void fun(int a, int b = 23 , int c = 8000); // 也可以是下列形式 void fun(int ,int = 23,int = 8000); // ok; #endif // A.cpp #includeusing namespace std; #include"A.h" //void fun(int a,int b = 10,int c = 20);//error; //定义中不再给出缺省值 void fun(int a, int b, int c) { cout << "a = " << a << " b = " << b << " c = " << c << endl; } // MainTest.cpp #include using namespace std; #include"A.h" int main() { fun(12); fun(10,20); fun(10,20,30); return 0; }
- 当缺省实参是一个表达式时 在函数被调用时该表达式被求值 。
实例:#includeusing namespace std; int my_rand() { srand(time(NULL)); int ra = rand() % 100; return ra; } void fun(int a, int b = my_rand()) { cout << "a = " << a << " b= " << b << endl; } int main() { fun(12); return 0; }



