int raiseToPower(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; ++i) result *= base;
return result;
}
int main() {
int threeExpFour = raiseToPower(3, 4); // 81
cout << "3^4 is " << threeExpFour << endl;
return 0;
}
函式宣告(原型)必須置於呼叫之前,或置於標頭檔供多檔案共用。
同名函式,參數列表不同(型別/數量/順序):
void printOnNewLine(int x) { cout << "1 Integer: " << x << endl; }
void printOnNewLine(int x, int y) { cout << "2 Integers: " << x << " and " << y << endl; }
編譯器依引數型別自動選擇對應版本。
| 方式 | 語法 | 特性 |
|---|---|---|
| 傳值 | void f(int a) | 複製副本,函式內修改不影響原變數 |
| 傳址 | void f(int &a) | 傳遞別名,函式內修改直接影響原變數 |
傳址可避免大型物件複製開銷,亦為「輸出參數」常用手法。