1、函数默认参数.cpp 851 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //函数默认参数
  2. //在C++中,函数的形参列表中的形参是可以有默认值的。
  3. //语法 : 返回值类型 函数名 (参数 = 默认值) {}
  4. #if(0)
  5. #include <iostream>
  6. //如果我们自己传入数据,就用自己的数据,如果没有,那么就用默认值
  7. //语法 : 返回值类型 函数名 (形参 = 默认值)
  8. int func(int a, int b = 20, int c = 30)
  9. {
  10. return a + b + c;
  11. }
  12. //注意事项
  13. //1、如果某个位置已经有了默认参数,那么从这个位置往后,从左到右必须都有默认值;
  14. //int func2(int a, int b = 10, int c, int d)
  15. //{
  16. // return a + b + c;
  17. //}
  18. //2、如果函数的声明有了默认,那么函数的实现就不能有默认参数
  19. //声明和实现只能有一个有默认参数
  20. int func2(int a , int b );
  21. int func2(int a = 10, int b = 10)
  22. {
  23. return a + b;
  24. }
  25. int main()
  26. {
  27. std::cout << func(10) << std::endl;
  28. std::cout << func2(10, 10) << std::endl;
  29. system("pause");
  30. return 0;
  31. }
  32. #endif