函数参数的默认值C++ 中可以在函数声明时为参数提供一个默认值当函数调用时没有提供参数的值,则使用默认值int mul(int x = 0);int main(int argc, char* argv[]){ printf("%d\n", mul()); // mul(0)}int mul(int x){ return x * x;}参数的默认值必须在函数声明中指定问题:函数定义中是否可以出现参数的默认值?当函数声明和定义中的参数默认值不同时会发生什么?当有函数声明时,函数定义中不可以出现默认参数,否则编译器报错;当没有函数声明时,函数定义中可以出现默认参数。int mul(int x = 0);// …int mul(int x = 5) // Error !!{ return x * x;}示例分析: 默认参数值初探#include <stdio.h>int mul(int x = 0);int main(int argc, char* argv[]){ printf("%d\n", mul()); printf("%d\n", mul(-1)); printf("%d\n", mul(2)); return 0;}int mul(int x){ return x * x;}输出:014函数默认参数规则参数的默认值必须从右向左提供(函数设计时)函数调用时使用了默认值,则后续参数必须使用默认值(函数调用时)int add(int x, int y = 1, int z = 2){ return x + y + z;}add(0); // x = 0, y = 1, z = 2add(2, 3); // x = 2, y = 3, z = 2add(3, 2, 1); // x = 3, y = 2, z = 1编程实验:默认参数示例#include <stdio.h>int add(int x, int y = 0, int z = 0);int main(int argc, char* argv[]){ printf("%d\n", add(1)); printf("%d\n", add(1, 2)); printf("%d\n", add(1, 2, 3)); return 0;}int add(int x, int y, int z){ return x + y + z;}输出:136函数占位参数在 C++ 中可以为函数提供占位参数占位参数只有参数类型声明,而没有参数名声明一般情况下,在函数体内部无法使用占位参数int func(int x, int){ return x;}// …func(1, 2);函数占位参数的意义占位参数与默认参数结合起来使用兼容 C 语言程序中可能出现的不规范写法下面的两种声明发生等价吗?void func(); <–> void func(void);C 中不等价:void func() 无返回值,可接受任意参数的函数; void func(void) 无返回值,无参数的函数C++ 中等价:无返回值,无参数的函数编程实验: 占位参数与默认参数值test.c#include <stdio.h>int func(){ return 99;}int main(int argc, char* argv[]){ printf("%d\n", func(1, 2, 3)); return 0;}test.cpp#include <stdio.h>int func(int = 0, int = 0, int = 0) // 为了兼容原有的 C 代码{ return 99;}int main(int argc, char* argv[]){ printf("%d\n", func(1, 2, 3)); return 0;}小结C++ 中支持函数参数的默认值如果函数调用没有提供参数值,则使用默认值参数的默认值必须从右向左提供函数调用时使用了默认值,则后续参数必须使用默认值C++ 中支持占位参数,用于兼容 C 语言中不规范写法以上内容参考狄泰软件学院系列课程,请大家保护原创!