定義 `Customer` 類(賬號、密碼、姓名、餘額),用**三種方式**重載 `-` 運算符,使兩個對象相減得到餘額之差。
#include <iostream>
#include <string>
using namespace std;
class Customer {
public:
string account, password, name;
double balance;
Customer(string acc, string pwd, string n, double b)
: account(acc), password(pwd), name(n), balance(b) {}
// 方式一:成員函數重載(左操作數為當前對象)
double operator-(const Customer& other) const {
return this->balance - other.balance;
}
// 方式二:友元函數重載(可訪問私有成員,雙向隱式轉換)
friend double operator-(const Customer& lhs, const Customer& rhs);
// 方式三:普通函數重載(需提供公有獲取器,此處為演示將 balance 設為 public)
// 實際項目中 balance 應 private,配合 getter 使用
};
// 方式二實現:友元函數(定義在類外)
double operator-(const Customer& lhs, const Customer& rhs) {
return lhs.balance - rhs.balance;
}
// 方式三:普通函數(同樣簽名,非友元,需 public 訪問權限)
// double operator-(const Customer& lhs, const Customer& rhs) { ... }
int main() {
Customer c1("001", "pwd1", "Alice", 1000.0);
Customer c2("002", "pwd2", "Bob", 600.0);
// 成員函數調用
cout << "c1 - c2 (member) = " << (c1 - c2) << endl; // 400
// 友元/普通函數調用(語法相同)
cout << "c1 - c2 (friend) = " << operator-(c1, c2) << endl; // 400
return 0;
}
| 方式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 成員函數 | 直觀、`this` 隱式傳遞、可訪問私有成員 | 左操作數**必須**為類對象,不支持隱式轉換 | 單邊操作、左操作數固定 |
| 友元函數 | 左右對稱、支持隱式轉換、可訪問私有成員 | 破壞封裝性、類外定義稍顯分散 | 雙邊操作、需隱式轉換(如 `5 - obj`) |
| 普通函數 | 不破壞封裝(配合 public getter)、編碼風格統一 | 無法直接訪問 private/protected 成員 | 成員均為 public 或提供 getter 時 |
掌握三種重載形式,靈活應對不同設計需求。