初學 C++ 時常見疑惑:void 函數無返回值,如何把運算結果「傳出去」?又如字串拼接與長度計算分離在兩個函數,如何協作?核心在於參數傳遞機制:值傳遞、指標傳遞、引用傳遞。本文以 str_cat (拼接) 與 str_len (長度) 為例詳細說明。
函數若需修改呼叫端的變數,參數必須是指標或引用。C 風格常用指標,C++ 推薦引用。
#include
#include
// 拼接:將 src 附加到 dest 末尾,並透過 lenPtr 回傳新長度
void str_cat(char *dest, const char *src, int *lenPtr) {
strcat(dest, src); // 需確保 dest 空間足夠
if (lenPtr) *lenPtr = strlen(dest); // 透過指標寫回長度
}
// 計算長度 (僅示範,實際可用 strlen)
int str_len(const char *s) {
return strlen(s);
}
int main() {
char s1[100] = "hello "; // 須預留足夠空間
char s2[] = "world";
int n = 0;
str_cat(s1, s2, &n); // 傳入 n 的位址
printf("拼接結果: %s\n", s1); // hello world
printf("長度: %d\n", n); // 11
// 若需用 str_len 驗證
printf("str_len 驗證: %d\n", str_len(s1));
return 0;
}
int *lenPtr:函數參數為指標,呼叫端傳 &n (位址)。*lenPtr = ...:在函數內透過解參考寫入值,呼叫端的 n 即被修改。dest 必須有足夠緩衝區 (如 char s1[100]),否則 strcat 會緩衝區溢位。#include
#include
// 使用引用 int& 作為輸出參數
void str_cat_cpp(char *dest, const char *src, int &len) {
strcat(dest, src);
len = strlen(dest); // 直接賦值,語法如同普通變數
}
int main() {
char s1[100] = "hello ";
char s2[] = "world";
int n = 0;
str_cat_cpp(s1, s2, n); // 呼叫時像傳值一樣,實為傳引用
std::cout << "結果: " << s1 << ", 長度: " << n << std::endl;
return 0;
}
&,程式碼更乾淨。std::string (現代 C++ 最佳實踐)手動管理 char* 緩衝區易出錯,C++ 標準庫 std::string 已內建拼接、長度、記憶體管理:
#include
#include
void str_cat_modern(std::string &dest, const std::string &src, int &len) {
dest += src; // 安全拼接
len = dest.size(); // 獲取長度
}
int main() {
std::string s1 = "hello ";
std::string s2 = "world";
int n = 0;
str_cat_modern(s1, s2, n);
std::cout << "結果: " << s1 << ", 長度: " << n << std::endl; // hello world, 11
return 0;
}
| 主題 | 建議閱讀章節 |
|---|---|
| 函數基礎、參數傳遞 (值/指標/引用) | 第 7 章:函數——C++ 的程式模塊 |
| 指標與記憶體模型 | 第 8 章:指標與自由儲存區 |
C 風格字串 (char*, cstring) | 第 4 章:複合類型 / 第 17 章:輸入輸出與文件 |
std::string 完整用法 | 第 4 章 / 第 16 章:string 類與標準模板庫 |
std::string + 引用參數,避免手動緩衝區管理與指標錯誤。