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

📅  最后修改于: 2020-09-25 04:49:38             🧑  作者: Mango

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

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

如果使用默认参数的函数调用时没有传递参数,则使用默认参数。

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

默认参数的工作

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

示例:默认参数

#include 
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: $$$$$

该程序的工作原理如下:

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

#include 
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;
}

要记住的事情