7.7 函式的預設參數
有些參數在大多數時候都用相同的值,每次都傳太麻煩。預設參數讓你在定義函式時指定「如果呼叫時沒傳這個參數,就用這個預設值」。
在函式定義時,用 = 指定參數的預設值。有預設值的參數必須是函式參數列表的最後連續一段。
void functionName(int a, int b = 10, int c = 20) {
// b 的預設值是 10,c 的預設值是 20
}
// ✗ 不合法:有預設值的參數後面跟著沒預設值的參數
void wrong(int a = 5, int b) { }
¶範例程式碼
#include<iostream>
using namespace std;
// 定義函式時指定預設值
int add(int x = 2, int y = 1) {
return x + y;
}
int subtract(int x, int y = 1) {
return x - y;
}
int main() {
// add 函式的各種呼叫方式
cout << add() << "\n"; // 沒傳參數,用預設值 2 + 1 = 3
cout << add(5) << "\n"; // 只傳 x,y 用預設值 5 + 1 = 6
cout << add(5, 6) << "\n"; // 傳全部參數 5 + 6 = 11
cout << "\n";
// subtract 函式的呼叫方式
cout << subtract(10) << "\n"; // 10 - 1 = 9
cout << subtract(10, 3) << "\n"; // 10 - 3 = 7
return 0;
}
執行結果:
3
6
11
9
7
動手試試看:定義一個 void printLine(char c = '*', int n = 10) 函式,印出 n 個字元 c 組成的一行。試試各種呼叫方式:printLine()、printLine('#')、printLine('#', 5)。