在 C++ 中函式中使用預設引數

Jinku Hu 2023年1月30日 2021年4月29日
  1. 使用預設引數在 C++ 中定義函式
  2. 在 C++ 中使用預設引數實現類建構函式
在 C++ 中函式中使用預設引數

本文將介紹幾種如何在 C++ 中為函式使用預設引數的方法。

使用預設引數在 C++ 中定義函式

預設引數的概念使得可以在函式定義中指定預設引數值,以防使用者未在其位置傳遞任何引數。因此,函式可以具有可選引數,該引數可以在函式內部使用一些預設值來初始化某些物件。在函式原型中,在每個引數名稱之後使用 = 符號和相應的值來指定預設引數。例如,以下程式碼段實現了一個 sumNumbers 函式模板,該模板最多可以對四個數字求和。但是,不需要使用者提供所有四個值。相反,僅兩個整數足以進行該操作。

#include <iostream>
#include <string>
#include <utility>
#include <vector>

using std::cout; using std::endl;
using std::string; using std::cin;
using std::vector;


template<typename T>
T sumNumbers(T x, T y, T z=0, T w=0)
{
    return (x + y + z + w);

}

int main(){
    vector<int> vec = {1, 4, 8, 16, 20, 24, 28, 32};

    for (size_t i = 0; i < vec.size(); ++i) {
        cout << sumNumbers(vec[i], vec[i+1]) << ": ";
    }
    cout << endl;

    for (size_t i = 0; i < vec.size(); ++i) {
        cout << sumNumbers(vec[i], vec[i+1], vec[i+2]) << ": ";
    }
    cout << endl;

    for (size_t i = 0; i < vec.size(); ++i) {
        cout << sumNumbers(vec[i], vec[i+1], vec[i+2], vec[i+3]) << ": ";
    }
    cout << endl;


    return EXIT_SUCCESS;
}

輸出:

5: 12: 24: 36: 44: 52: 60: 32
13: 28: 44: 60: 72: 84: 60: 32:
29: 48: 68: 88: 104: 84: 60: 4145:

在 C++ 中使用預設引數實現類建構函式

可以利用預設引數的概念的另一個有用場景是類建構函式。有時,如果使用者不提供引數,則類建構函式可能需要使用預設值初始化一些資料成員。我們可以使用預設引數實現一個建構函式,該建構函式呼叫另一個具有預設值的建構函式,如下面的示例程式碼所示。

#include <iostream>
#include <string>
#include <utility>
#include <vector>

using std::cout; using std::endl;
using std::string; using std::cin;
using std::vector;

class MyClass {
    string name;
    int height;
    int width;
public:
    MyClass(string s, int h, int w):
            name(std::move(s)), height(h), width(w) {}
    MyClass(): MyClass("", 0, 0) {}
    explicit MyClass(string s): MyClass(std::move(s), 0,0) {}

    void printMyClass() {
        cout << "name: " << name << endl
             << "height: " << height << endl
             << "width: " << width << endl;
    }
};

int main(){
    MyClass M1;
    MyClass M2("Jay", 12, 103);

    M1.printMyClass();
    cout << endl;
    M2.printMyClass();

    return EXIT_SUCCESS;
}

輸出:

name:
height: 0
width: 0


name: Jay
height: 12
width: 103
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Function