• C++默认参数(实参)


            在本文中,您将学习什么是默认参数,如何使用它们以及使用它的必要声明。在C ++编程中,您可以提供函数参数的默认值。默认参数背后的想法很简单。如果通过传递参数调用函数,则这些参数将由函数使用。但是,如果在调用函数时未传递参数,则使用默认值。默认值传递给函数原型中的参数。

    默认参数的工作

     case1:

    1. # include
    2. using namespace std;
    3. void temp(int = 10, float = 8.8);
    4. int main() {
    5. temp();
    6. return 0;
    7. }
    8. void temp(int i, float f) {
    9. cout << i << endl; // 10
    10. cout << f; // 8.8
    11. }

    case2: 

    1. # include
    2. using namespace std;
    3. void temp(int = 10, float = 8.8);
    4. int main() {
    5. temp(6);
    6. return 0;
    7. }
    8. void temp(int i, float f) {
    9. cout << i << endl; // 6
    10. cout << f; // 8.8
    11. }

    case3:
     

    1. # include
    2. using namespace std;
    3. void temp(int = 10, float = 8.8);
    4. int main() {
    5. temp(6,-2.3);
    6. return 0;
    7. }
    8. void temp(int i, float f) {
    9. cout << i << endl; // 6
    10. cout << f; // -2.3
    11. }

    case4:

    1. # include
    2. using namespace std;
    3. void temp(int = 10, float = 8.8);
    4. int main() {
    5. temp(3.4);
    6. return 0;
    7. }
    8. void temp(int i, float f) {
    9. cout << i << endl; // 3
    10. cout << f; // 8.8
    11. }

     示例:默认参数

    1. // c++程序演示默认参数的工作方式
    2. # include
    3. using namespace std;
    4. void display(char = '*', int = 1);
    5. int main() {
    6. cout << "没有参数传递:\n";
    7. display();
    8. cout << "\n第一个参数被传递:\n";
    9. display('!');
    10. cout << "\n两个参数均被传递:\n";
    11. display('&', 5);
    12. return 0;
    13. }
    14. void display(char c, int n) {
    15. for (int i = 1; i <= n; i++) {
    16. cout << c;
    17. }
    18. cout << endl;
    19. }

     运行结果:

    1. 没有参数传递:
    2. *
    3. 第一个参数被传递:
    4. !
    5. 两个参数均被传递:
    6. &&&&&

    在上面的程序中,您可以看到分配默认值给参数 void display(char ='*',int = 1);。
            首先,在display()不传递任何参数的情况下调用函数。在这种情况下,display()函数同时使用了默认参数c = *和n = 1。
            然后,第二次使用该函数只传递第一个参数。在这种情况下,函数不使用传递的第一个默认值。它使用作为第一个参数传递的实际参数c = !,并将默认值n = 1作为第二个参数。
            当第三次display()被调用时传递两个参数,都不使用默认参数。传递的值分别为 c = &和n = 5.

    使用默认参数时的常见错误

    1. void add(int a, int b = 3, int c, int d = 4);
      上面的函数将无法编译。您不能跳过两个参数之间的默认参数。
      在这种情况下,c还应分配一个默认值。

    2. void add(int a, int b = 3, int c, int d);
      上面的函数也不会编译。您必须在b之后为每个参数提供默认值。
      在这种情况下,c和d也应该被分配缺省值。
      如果只需要一个默认参数,请确保该参数是最后一个参数。如:void add(int a, int b, int c, int d = 4);

    3. 如果您的函数执行了多项操作,或者逻辑看起来过于复杂,则可以使用  函数重载更好地分离逻辑。

    4. 无论如何使用默认参数,都应该始终编写一个函数,使它只用于一个目的。

     

  • 相关阅读:
    【爬虫进阶】猿人学任务六之回溯(难度3.0)
    关于【Java】中(类)需要知道的
    RabbitMQ消息可靠性问题
    机器人相关课程考核材料归档实施细则2022版本
    【慢SQL性能优化】 一条SQL的生命周期
    C++ decltype 类型推导
    MongoDB磁盘空间占满,导致数据库被锁定,如何清理数据和磁盘空间
    go使用grpc
    “百花齐放、百家争鸣”,数据可视化呈现我国科学文化的发展
    【C语言】二分查找(含图解)
  • 原文地址:https://blog.csdn.net/m0_48241022/article/details/133653070