| 場景 | 推薦寫法 | 理由 |
| 運算子需存取 private | 友元函數 | 語意對稱(左/右運算元地位相同) |
| 單邊運算子(如 +=) | 成員函數 | 左運算元必須為類別物件 |
| 雙元運算子(+, -, *, /) | 友元函數 | 支援隱式轉換(如 Complex + double) |
修正程式碼:僅保留友元版
class Complex {
double real, imag;
public:
Complex(double r=0, double i=0): real(r), imag(i) {}
// 移除成員 operator+ / operator-
friend Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
friend Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.imag - b.imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
return os << '(' << c.real << ',' << c.imag << ')';
}
};
驗證測試
int main() {
Complex c1(5,4), c2(2,10), c3;
c3 = c1 + c2; // 呼叫友元 operator+
c3 = c3 - c1; // 呼叫友元 operator-
cout << c3; // 友元 operator<<
return 0;
}
進階:支援混合型別運算
friend Complex operator+(const Complex& a, double b) {
return Complex(a.real + b, a.imag);
}
friend Complex operator+(double a, const Complex& b) {
return Complex(a + b.real, b.imag);
}
總結
同一運算子不可同時定義成員版與友元版。雙元算術運算子推薦使用友元函數,確保對稱性、隱式轉換支援且避免二義性。
- 上一篇文章: ASP 動態新增表格列資料提交:Request.Form 陣列遍歷與同名輸入框處理
- 下一篇文章: C 語言陣列計算產品總成本:固定成本與變動成本陣列索引對應實作
Copyright ©
程式碼之家 All Rights Reserved