当前位置:首页 > 编程笔记 > 正文
已解决

C++默认参数(实参)

来自网友在路上 151851提问 提问时间:2023-10-07 22:30:56阅读次数: 51

最佳答案 问答题库518位专家为你答疑解惑

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

默认参数的工作

 case1:

# include <iostream>
using namespace std;void temp(int = 10, float = 8.8);int main() {temp();return 0;
}void temp(int i, float f) {cout << i << endl; // 10cout << f; // 8.8
}

case2: 

# include <iostream>
using namespace std;void temp(int = 10, float = 8.8);int main() {temp(6);return 0;
}void temp(int i, float f) {cout << i << endl; // 6cout << f; // 8.8
}

case3:
 

# include <iostream>
using namespace std;void temp(int = 10, float = 8.8);int main() {temp(6,-2.3);return 0;
}void temp(int i, float f) {cout << i << endl; // 6cout << f; // -2.3
}

case4:

# include <iostream>
using namespace std;void temp(int = 10, float = 8.8);int main() {temp(3.4);return 0;
}void temp(int i, float f) {cout << i << endl; // 3cout << f; // 8.8
}

 示例:默认参数

// c++程序演示默认参数的工作方式
# include <iostream>
using namespace std;void display(char = '*', int = 1);int main() {cout << "没有参数传递:\n";display();cout << "\n第一个参数被传递:\n";display('!');cout << "\n两个参数均被传递:\n";display('&', 5);return 0;
}void display(char c, int n) {for (int i = 1; i <= n; i++) {cout << c;}cout << endl;
}

 运行结果:

没有参数传递:
*第一个参数被传递:
!两个参数均被传递:
&&&&&

在上面的程序中,您可以看到分配默认值给参数 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. 无论如何使用默认参数,都应该始终编写一个函数,使它只用于一个目的。

 

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"C++默认参数(实参)":http://eshow365.cn/6-16975-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!