C 允許隱式 int,C++ **嚴禁**。無返回值必寫 void。
**反面教材**:getchar。
char c;
c = getchar(); // 直覺以為回傳 char
if (c == EOF) ... // EOF 通常為 -1 (int)
int getchar(void); // 真實原型:int!
原因:正常回傳字元,但需區分 EOF/錯誤,**只能擴大返回型別容納標誌值**。
正常值用輸出參數,錯誤標誌用返回值。
// 改良版
BOOL GetChar(char* c); // 返回 TRUE/FALSE 表成功失敗,字元經 c 輸出
// 原版靈活但危險
putchar(getchar()); // 合法但誤用後果嚴重
char* strcpy(char* dest, const char* src); // 返回 dest
int len = strlen(strcpy(buf, "Hello")); // 一行完成複製+取長
String& String::operator=(const String& other) {
if (this == &other) return *this;
delete m_data;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data);
return *this; // ✅ 引用,零拷貝
}
值傳回會觸發拷貝建構:a = b 1 次,a = b = c 2 次,**純屬浪費**。
String operator+(const String& s1, const String& s2) {
String temp;
// ... 組合 ...
return temp; // ✅ 值傳回,編譯器 NRVO 優化
}
引用傳回 temp → 區域物件銷毀後懸空,**嚴禁**。