首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 運算符重載實戰:Stonewt 類別的六大關係運算符實現與應用

     編輯:程式設計疑難解答

在 C++ 程式設計中,運算符重載是賦予自定義類別直觀操作能力的關鍵技術。本文將透過一個經典的 Stonewt(英石/磅)類別案例,詳細講解如何重載全部 6 個關係運算符(>、<、==、>=、<=、!=),並結合陣列操作演示如何尋找最大值、最小值以及統計符合條件的元素數量。

核心需求分析

題目要求設計一個 Stonewt 類別,內部以 stone(英石)和 pounds(磅)兩個成員變數儲存重量。需實現以下功能:

  • 重載 6 個關係運算符,比較邏輯基於總重量(換算為磅),返回 bool 值。
  • 宣告包含 6 個 Stonewt 物件的陣列,前 3 個在宣告時初始化,後 3 個透過迴圈讀取輸入初始化。
  • 遍歷陣列,輸出最大元素、最小元素,以及重量大於或等於 11 英石的元素個數。

類別設計與運算符重載實現

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;
}

關鍵技術點總結

  1. 運算符重載原則:優先實現 ==、<、> 核心比較,其餘運算符(>=、<=、!=)透過組合核心運算符實現,確保邏輯一致性且減少代碼冗餘。
  2. Const 正確性:所有運算符成員函式均標記為 const,參數採用 const 引用,保證不修改操作數,符合最佳實踐。
  3. 陣列初始化靈活性:C++ 允許陣列宣告時部分初始化,剩餘元素稍後賦值,適應動態輸入場景。
  4. 邊界條件處理:初始化 max、min 為首元素,避免空陣列或未初始化比較導致的未定義行為。

透過此案例,不僅掌握了運算符重載的語法與技巧,更理解了如何將現實世界的度量單位轉換封裝於類別內部,對外提供清晰、直觀的介面,這正是物件導向設計的精髓所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved