在 C++ 程式設計中,運算符重載是賦予自定義類別直觀操作能力的關鍵技術。本文將透過一個經典的 Stonewt(英石/磅)類別案例,詳細講解如何重載全部 6 個關係運算符(>、<、==、>=、<=、!=),並結合陣列操作演示如何尋找最大值、最小值以及統計符合條件的元素數量。
題目要求設計一個 Stonewt 類別,內部以 stone(英石)和 pounds(磅)兩個成員變數儲存重量。需實現以下功能:
bool 值。Stonewt 物件的陣列,前 3 個在宣告時初始化,後 3 個透過迴圈讀取輸入初始化。Stonewt 類別提供三種建構函式:預設建構、單一 double 磅數建構、以及 int stone, double pounds 建構。核心邏輯在於將英石統一換算為磅進行比較(1 stone = 14 pounds)。
#include <iostream>
using namespace std;
class Stonewt {
private:
int stone;
double pounds;
public:
Stonewt() : stone(0), pounds(0.0) {}
Stonewt(double lbs) {
stone = int(lbs) / 14;
pounds = lbs - (int(lbs) / 14 * 14);
}
Stonewt(int stn, double lbs) {
stone = stn + int(lbs) / 14;
pounds = lbs - (int(lbs) / 14 * 14);
}
void show() const { cout << stone << "stn " << pounds << "lbs." << endl; }
// 核心比較邏輯:先比 stone,相同則比 pounds
bool operator>(const Stonewt &s) const {
return (stone > s.stone) || (stone == s.stone && pounds > s.pounds);
}
bool operator<(const Stonewt &s) const {
return (stone < s.stone) || (stone == s.stone && pounds < s.pounds);
}
bool operator==(const Stonewt &s) const {
return stone == s.stone && pounds == s.pounds;
}
// 其餘運算符基於基礎運算符組合,避免邏輯重複
bool operator>=(const Stonewt &s) const { return *this > s || *this == s; }
bool operator<=(const Stonewt &s) const { return *this < s || *this == s; }
bool operator!=(const Stonewt &s) const { return !(*this == s); }
};
main 函式展示了陣列的初始化、輸入處理、遍歷比較及結果輸出的完整流程。
int main() {
// 前三個初始化,後三個透過賦值初始化
Stonewt arr[6] = { Stonewt(28.5), Stonewt(50.1), Stonewt(1, 2.1) };
arr[3] = Stonewt(1, 20.0);
arr[4] = Stonewt(12, 0.4);
arr[5] = Stonewt(12, 0.6);
Stonewt max = arr[0], min = arr[0];
int count_ge_11 = 0;
Stonewt threshold(11, 0.0); // 11 英石門檻
for (int i = 0; i < 6; ++i) {
arr[i].show();
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
if (arr[i] >= threshold) ++count_ge_11;
}
cout << "max "; max.show();
cout << "min "; min.show();
cout << ">= 11 stone: " << count_ge_11 << endl;
return 0;
}
==、<、> 核心比較,其餘運算符(>=、<=、!=)透過組合核心運算符實現,確保邏輯一致性且減少代碼冗餘。const,參數採用 const 引用,保證不修改操作數,符合最佳實踐。max、min 為首元素,避免空陣列或未初始化比較導致的未定義行為。透過此案例,不僅掌握了運算符重載的語法與技巧,更理解了如何將現實世界的度量單位轉換封裝於類別內部,對外提供清晰、直觀的介面,這正是物件導向設計的精髓所在。