亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C++ 编程默认参数(参数)

C++ 编程默认参数(参数)

在本教程中,我们将借助示例学习 C++ 默认参数及其工作原理。

在C++编程中,我们可以为函数参数提供默认值。

如果调用具有默认参数的函数而不传递参数,则使用默认参数。

但是,如果在调用函数时传递参数,则默认参数将被忽略。


默认参数的工作

<图>

我们可以从上图了解默认参数的工作原理:

  1. temp() 被调用,两个默认参数都被函数使用。
  2. temp(6) 被调用,第一个参数变成 6 而第二个参数使用默认值。
  3. temp(6, -2.3) 被调用,两个默认参数都被覆盖,导致i = 6f = -2.3 .
  4. temp(3.4) 被传递时,函数会以不希望的方式运行,因为如果不传递第一个参数,则无法传递第二个参数。

    因此,3.4 作为第一个参数传递。由于第一个参数被定义为 int ,实际传递的值是3 .

示例:默认参数

#include <iostream>
using namespace std;

// defining the default arguments
void display(char = '*', int = 3);

int main() {
    int count = 5;

    cout << "No argument passed: ";
    // *, 3 will be parameters
    display(); 
    
    cout << "First argument passed: ";
     // #, 3 will be parameters
    display('#'); 
    
    cout << "Both arguments passed: ";
    // $, 5 will be parameters
    display('$', count); 

    return 0;
}

void display(char c, int count) {
    for(int i = 1; i <= count; ++i)
    {
        cout << c;
    }
    cout << endl;
}

输出

No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$

下面是这个程序的工作原理:

  1. display() 在不传递任何参数的情况下调用。在这种情况下,display() 使用两个默认参数 c = '*'n = 1 .
  2. display('#') 只用一个参数调用。在这种情况下,第一个变为 '#' .第二个默认参数n = 1 被保留。
  3. display('#', count) 用两个参数调用。在这种情况下,不使用默认参数。

我们还可以在函数定义本身中定义默认参数。下面的程序和上面的程序是等价的。

#include <iostream>
using namespace std;

// defining the default arguments
void display(char c = '*', int count = 3) {
    for(int i = 1; i <= count; ++i) {
        cout << c;
    }
    cout << endl;
}

int main() {
    int count = 5;

    cout << "No argument passed: ";
    // *, 3 will be parameters
    display(); 
    
    cout << "First argument passed: ";
     // #, 3 will be parameters
    display('#'); 
    
    cout << "Both argument passed: ";
    // $, 5 will be parameters
    display('$', count); 

    return 0;
}

要记住的事情

  1. 一旦我们为参数提供了默认值,所有后续参数也必须具有默认值。例如,
    // Invalid
    void add(int a, int b = 3, int c, int d);
    
    // Invalid
    void add(int a, int b = 3, int c, int d = 4);
    
    // Valid
    void add(int a, int c, int b = 3, int d = 4);
  2. 如果我们在函数定义而不是函数原型中定义默认参数,那么函数必须在函数调用之前定义。
    // Invalid code
    
    int main() {
        // function call
        display();
    }
    
    void display(char c = '*', int count = 5) {
        // code
    }

C语言

  1. C# 编程中的命名空间
  2. C++ 运算符
  3. C++ 注释
  4. 在 C++ 编程中将数组传递给函数
  5. C++ 类模板
  6. C 编程运算符
  7. C 编程中用户定义函数的类型
  8. C++ 变量和类型:int、double、char、string、bool
  9. C 教程
  10. C - 函数
  11. C - 变量参数
  12. C++ 概述