Skip to content

Latest commit

 

History

History
147 lines (101 loc) · 3.58 KB

File metadata and controls

147 lines (101 loc) · 3.58 KB

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

原文: https://www.programiz.com/cpp-programming/default-argument

在本教程中,我们将通过示例学习 C++ 默认参数及其使用。

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

如果在不传递参数的情况下调用具有默认参数的函数,则使用默认参数。

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


默认参数的工作原理

Working of Default Arguments in C++

C++ 中的默认参数如何工作

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

  1. 调用temp()时,该函数使用两个默认参数。

  2. 调用temp(6)时,第一个参数变为10,而第二个参数使用默认值。

  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
    }