ο髮崙?zhàn):多項式類與String類的內(nèi)存安全實現(xiàn))
簡介本資源是吉林大學(xué)《面向?qū)ο蟪绦蛟O(shè)計》課程配套的C上機實驗報告面向計算機專業(yè)本科生及C初學(xué)者聚焦面向?qū)ο蠛诵哪芰τ?xùn)練解決多項式類設(shè)計中動態(tài)內(nèi)存管理、運算符重載、多文件組織等典型實踐難點。壓縮包為單個303KB的Word文檔.doc完整呈現(xiàn)了從需求分析、類設(shè)計Polynomial.h/.cpp、關(guān)鍵代碼實現(xiàn)含構(gòu)造/析構(gòu)/拷貝構(gòu)造、input/output/calculate函數(shù)、運算符重載細節(jié)、-、*、含友元考量到主函數(shù)測試的全流程附有靜態(tài)成員計數(shù)、錯誤輸入處理、系數(shù)為0的輸出優(yōu)化等工程化細節(jié)。已有1810人學(xué)習(xí)下載讀者可直接復(fù)用該報告結(jié)構(gòu)撰寫課程作業(yè)深入理解類封裝、資源管理與const成員函數(shù)設(shè)計原則并獲得可編譯運行的完整多文件代碼框架與規(guī)范注釋。1. 這不是一份交差作業(yè)而是一套能跑通、能調(diào)試、能改出新功能的 C 面向?qū)ο髮崙?zhàn)模板你有沒有遇到過這種場景剛學(xué)完 C 類、構(gòu)造函數(shù)、運算符重載一寫多項式就卡在new和delete[]的配對上輸入一個系數(shù)輸錯程序直接崩兩個多項式相乘結(jié)果全是亂碼operator寫完一運行就報double free or corruption這不是你手生——是原始實驗報告里藏著一堆沒填坑的內(nèi)存黑匣子、沒聲明 const 的接口、沒處理邊界 case 的輸出邏輯更別說多文件編譯時頭文件循環(huán)包含、靜態(tài)成員未初始化、友元函數(shù)缺失這些“玄學(xué)翻車點”。這份來自吉林大學(xué)《面向?qū)ο蟪绦蛘n程設(shè)計》的上機實驗報告表面看是五份獨立 C 實驗多項式類、String 類、繼承體系、工資系統(tǒng)、圖形管理但實際是一套完整覆蓋 C 核心機制的工程化訓(xùn)練鏈從動態(tài)內(nèi)存管理A 部分、深拷貝/淺拷貝陷阱E 部分到訪問控制與繼承語義C 部分、抽象基類與多態(tài)調(diào)度D 部分再到資源封裝與 RAII 初探B 部分。它不教你怎么背語法而是逼你在cin 崩潰后查cin.clear()在p[i]越界后補n1容量在operator返回臨時對象時確認析構(gòu)時機——每一處報錯都是 C 編譯器在給你發(fā) debug 提示。如果你正卡在“知道概念但寫不出可運行代碼”的階段或者想用一個真實項目驗證自己對const成員函數(shù)、static生命周期、protected繼承邊界的理解這份報告就是你的最小可行練兵場。它不追求炫技但每行代碼都直指 C 工程落地中最容易踩的坑。接下來我會帶你把這份報告里的五組源碼真正變成你本地能g -stdc11編譯、能 gdb 調(diào)試、能加日志驗證、能安全二次開發(fā)的可執(zhí)行資產(chǎn)。2. 多項式類Polynomial動態(tài)數(shù)組 運算符重載的完整閉環(huán)實現(xiàn)這份實驗最硬核的部分不是寫個operator而是讓整個類在任意輸入、任意運算組合下不崩潰、不越界、不泄漏。原始報告里Polynomial.h和Polynomial.cpp存在多處關(guān)鍵缺陷默認構(gòu)造函數(shù)分配了n0的數(shù)組卻未置零、output()函數(shù)對系數(shù)為 ±1 的項處理不全、calculate()用pow(x,i)引入浮點誤差且未處理x0邊界。我們先修復(fù)結(jié)構(gòu)再逐模塊拆解。2.1 目錄結(jié)構(gòu)與編譯命令從混亂到清晰原始報告中文件名大小寫不統(tǒng)一Ploynomial.cppvsPolynomial.h、頭文件宏定義不一致#ifndef POLYNOMIALvs#ifndef STRING_H_、主函數(shù)分散在多個.cpp文件里。這會導(dǎo)致g main.cpp Polynomial.cpp時鏈接失敗或#include Polynomial.h找不到文件。規(guī)范后的目錄結(jié)構(gòu)推薦polynomial/ ├── include/ │ └── Polynomial.h // 統(tǒng)一宏定義#ifndef POLYNOMIAL_H_ ├── src/ │ ├── Polynomial.cpp // 實現(xiàn)所有成員函數(shù) │ └── main.cpp // 唯一入口測試全部功能 └── CMakeLists.txt // 可選但強烈建議關(guān)鍵編譯命令Linux/macOS# 單文件快速驗證跳過頭文件依賴 g -stdc11 -o poly src/Polynomial.cpp src/main.cpp # 帶警告的生產(chǎn)級編譯必須加 g -stdc11 -Wall -Wextra -Werror -o poly src/Polynomial.cpp src/main.cpp # 運行 ./poly提示-Wall -Wextra -Werror是 C 開發(fā)的后悔藥。原始代碼中p[0] \0給 int 數(shù)組賦 char 值、for (int i n; i 0; i--)i 為無符號時死循環(huán)等隱患開這些警告會直接報錯逼你修復(fù)。2.2 核心類定義補齊 const、static、友元三大要素原始Polynomial.h缺失const修飾、static計數(shù)器未聲明、operator未定義。修復(fù)后的頭文件關(guān)鍵段如下// include/Polynomial.h #ifndef POLYNOMIAL_H_ #define POLYNOMIAL_H_ #include iostream #include cmath // 用于 calculate但注意應(yīng)避免 pow()見后文 #include vector // 更安全的替代方案此處先保留原邏輯 class Polynomial { private: int n; // 最高次數(shù) int* p; // 動態(tài)數(shù)組p[i] 表示 x^i 的系數(shù) static int count; // 靜態(tài)成員已創(chuàng)建的 Polynomial 對象總數(shù) public: // 構(gòu)造函數(shù)族 Polynomial(); // 默認構(gòu)造n0, pnullptr explicit Polynomial(int degree); // 顯式構(gòu)造分配 degree1 個 int Polynomial(const Polynomial other); // 拷貝構(gòu)造深拷貝 ~Polynomial(); // 析構(gòu)釋放 p // 輸入輸出非 const因修改對象狀態(tài) void input(); void output() const; // 關(guān)鍵output 不修改對象聲明為 const // 計算const因只讀取對象數(shù)據(jù) double calculate(int x) const; // 返回值而非 void cout // 運算符重載返回新對象不修改 this Polynomial operator(const Polynomial rhs) const; Polynomial operator-(const Polynomial rhs) const; Polynomial operator*(const Polynomial rhs) const; Polynomial operator(const Polynomial rhs); // 賦值返回引用 // 友元函數(shù)支持 cout poly friend std::ostream operator(std::ostream os, const Polynomial poly); }; // 靜態(tài)成員定義必須在 .cpp 中不能在頭文件內(nèi) // extern int Polynomial::count; // 錯誤這是聲明不是定義 // 正確做法見 2.3 節(jié) #endif // POLYNOMIAL_H_參數(shù)說明與設(shè)計理由explicit Polynomial(int degree)加explicit防止隱式轉(zhuǎn)換如Polynomial p 5;這是 C 現(xiàn)代實踐。output() const和calculate() const明確告訴編譯器和調(diào)用者“此函數(shù)不改變對象狀態(tài)”提升可讀性與安全性。static int count記錄對象數(shù)量需在.cpp中定義并初始化int Polynomial::count 0;否則鏈接時報undefined reference。friend std::ostream operator讓std::cout p1;可用比p1.output()更符合 C 習(xí)慣。2.3 關(guān)鍵成員函數(shù)實現(xiàn)內(nèi)存安全與邊界處理原始Polynomial.cpp中input()函數(shù)對錯誤輸入的處理不徹底output()對x^1、x^0、系數(shù) ±1 的格式化有遺漏calculate()用pow()引入精度問題。以下是修復(fù)后的核心實現(xiàn)src/Polynomial.cpp// src/Polynomial.cpp #include include/Polynomial.h #include iostream #include iomanip // 用于 setw控制輸出對齊可選 #include algorithm // 用于 std::max // 靜態(tài)成員定義必須 int Polynomial::count 0; // 默認構(gòu)造n0, pnullptr更安全避免 new int[0] Polynomial::Polynomial() : n(0), p(nullptr) { count; } // 顯式構(gòu)造分配 degree1 個 int全部初始化為 0 Polynomial::Polynomial(int degree) : n(degree), p(new int[degree 1]()) { // () 初始化為 0避免垃圾值 count; } // 拷貝構(gòu)造深拷貝 Polynomial::Polynomial(const Polynomial other) : n(other.n), p(new int[other.n 1]) { for (int i 0; i other.n; i) { p[i] other.p[i]; } count; } // 析構(gòu)安全釋放 Polynomial::~Polynomial() { delete[] p; // 注意delete[]不是 delete --count; } // 輸入帶完整錯誤處理 void Polynomial::input() { std::cout 請輸入多項式的最高次數(shù) n (0): ; while (!(std::cin n) || n 0) { std::cin.clear(); // 清除錯誤標志 std::cin.ignore(10000, \n); // 丟棄錯誤輸入的整行 std::cout 輸入錯誤n 必須是非負整數(shù)請重新輸入: ; } // 釋放舊內(nèi)存如果存在 delete[] p; p new int[n 1](); // 分配并初始化為 0 std::cout 請按升序輸入系數(shù)a0, a1, ..., an空格分隔: ; for (int i 0; i n; i) { while (!(std::cin p[i])) { std::cin.clear(); std::cin.ignore(10000, \n); std::cout 系數(shù) i 輸入錯誤請重新輸入: ; } } } // 輸出嚴格按 -x^4-6x^35 格式處理所有邊界 void Polynomial::output() const { if (n 0 p[0] 0) { std::cout 0; return; } bool firstTerm true; // 從最高次項開始遍歷 for (int i n; i 0; --i) { if (p[i] 0) continue; // 跳過系數(shù)為 0 的項 if (!firstTerm) { std::cout (p[i] 0 ? : - ); } else { if (p[i] 0) std::cout -; } int absCoeff std::abs(p[i]); if (i 0) { // 常數(shù)項直接輸出系數(shù)絕對值 std::cout absCoeff; } else if (i 1) { // x^1 項輸出系數(shù)若為1則省略 x if (absCoeff 1) { std::cout x; } else { std::cout absCoeff x; } } else { // x^i 項輸出系數(shù)若為1則省略 x^ i if (absCoeff 1) { std::cout x^ i; } else { std::cout absCoeff x^ i; } } firstTerm false; } if (firstTerm) std::cout 0; // 全零多項式 } // 計算用霍納法Horners method替代 pow()避免浮點誤差和性能問題 double Polynomial::calculate(int x) const { if (n 0) return 0.0; if (n 0) return static_castdouble(p[0]); double result static_castdouble(p[n]); for (int i n - 1; i 0; --i) { result result * x p[i]; } return result; } // 友元輸出流重載 std::ostream operator(std::ostream os, const Polynomial poly) { poly.output(); return os; }邏輯說明與參數(shù)詳解input()用while (!(std::cin n) || n 0)同時檢查輸入流狀態(tài)和業(yè)務(wù)邏輯n≥0std::cin.ignore(10000, \n)比while (cin.get() ! \n)更魯棒防止緩沖區(qū)殘留。output()核心是firstTerm標志位。首項不加/-后續(xù)項根據(jù)系數(shù)正負決定符號absCoeff 1時省略系數(shù)如x^2而非1x^2i0和i1單獨處理確保5和3x格式正確。calculate()霍納法是重點。原始pow(x,i)在x10, i10時計算10^10不僅慢且pow()返回doubleint系數(shù)轉(zhuǎn)double再乘可能丟失精度。霍納法((a_n * x a_{n-1}) * x ...)全整數(shù)運算精準高效。operator作為友元可直接訪問poly.output()保持接口一致性。2.4 運算符重載實現(xiàn)深拷貝、內(nèi)存分配與異常安全原始Operation.cpp中operator和operator*存在嚴重缺陷operator未處理n不同導(dǎo)致的數(shù)組越界operator*的嵌套循環(huán)中multiply.p[i j]可能越界ij最大為ndxs.n但multiply.p只分配了ndxs.n1索引0..ndxs.n合法ij正好在此范圍但原始代碼multiply.p[i j] multiply.p[i j] temp[j];未初始化multiply.p為 0導(dǎo)致垃圾值累加。修復(fù)后的operator和operator*接續(xù)Polynomial.cpp// 加法結(jié)果次數(shù)為 max(n, rhs.n)系數(shù)對應(yīng)相加 Polynomial Polynomial::operator(const Polynomial rhs) const { int maxN std::max(n, rhs.n); Polynomial result(maxN); // 將當前對象系數(shù)復(fù)制到 result for (int i 0; i n i maxN; i) { result.p[i] p[i]; } // 將 rhs 系數(shù)加到 result for (int i 0; i rhs.n i maxN; i) { result.p[i] rhs.p[i]; } return result; // RVO 優(yōu)化無需額外拷貝 } // 乘法結(jié)果次數(shù)為 n rhs.n使用標準卷積 Polynomial Polynomial::operator*(const Polynomial rhs) const { if (n 0 || rhs.n 0) return Polynomial(0); // 邊界處理 int resultN n rhs.n; Polynomial result(resultN); // 初始化 result.p 為 0由構(gòu)造函數(shù)保證 // 卷積result.p[k] sum_{ijk} p[i] * rhs.p[j] for (int i 0; i n; i) { for (int j 0; j rhs.n; j) { result.p[i j] p[i] * rhs.p[j]; } } return result; } // 賦值運算符經(jīng)典三步法檢查自賦值、釋放舊資源、深拷貝 Polynomial Polynomial::operator(const Polynomial rhs) { if (this rhs) return *this; // 自賦值檢查 delete[] p; // 釋放當前資源 n rhs.n; p new int[n 1]; for (int i 0; i n; i) { p[i] rhs.p[i]; } return *this; }關(guān)鍵點解析operator用std::max(n, rhs.n)確定結(jié)果次數(shù)循環(huán)中i n i maxN防止p[i]越界當rhs.n n時i只遍歷到n。operator*雙重循環(huán)實現(xiàn)數(shù)學(xué)卷積result.p[ij] p[i] * rhs.p[j]是核心。result構(gòu)造時已用()初始化為 0確保累加正確。operator三步法是鐵律。原始代碼缺失自賦值檢查if (this rhs)若p1 p1先delete[] p再p[i] rhs.p[i]會訪問已釋放內(nèi)存必崩。3. String 類手動內(nèi)存管理與 RAII 思想的啟蒙實踐B 部分的String類看似簡單實則是 C 內(nèi)存管理的“照妖鏡”。原始String.h中cat()函數(shù)有致命 bugstrcat(str,st.str)修改了this-str但未檢查this-str容量是否足夠?qū)е戮彌_區(qū)溢出String::String(const char * s)未處理s為nullptr的情況operator的is.get(temp,max)未檢查temp是否以\0結(jié)尾。這些不是小疏忽而是 C 程序員必須刻進 DNA 的安全紅線。3.1 類接口重構(gòu)從“能用”到“健壯”原始String類缺少移動語義C11、c_str()接口、operator[]下標訪問且cat()命名不達意應(yīng)為append。我們按現(xiàn)代 C 習(xí)慣重構(gòu)// include/String.h #ifndef STRING_H_ #define STRING_H_ #include iostream #include cstring #include cstdlib // for strlen, strcpy, strcat class String { private: char* str; // 指向堆內(nèi)存的指針 size_t len; // 當前長度不含 \0 public: // 構(gòu)造 String(); // 空字符串 String(const char* s); // 從 C 字符串構(gòu)造 String(const String other); // 拷貝構(gòu)造 String(String other) noexcept; // 移動構(gòu)造C11 // 析構(gòu) ~String(); // 賦值 String operator(const String other); // 拷貝賦值 String operator(String other) noexcept; // 移動賦值 // 訪問 size_t length() const { return len; } const char* c_str() const { return str; } char operator[](size_t i) { return str[i]; } // 可修改 const char operator[](size_t i) const { return str[i]; } // 只讀 // 連接更名 append語義清晰 String append(const String other); // 友元流操作符 friend std::ostream operator(std::ostream os, const String s); friend std::istream operator(std::istream is, String s); }; #endif // STRING_H_設(shè)計意圖size_t len比int len更符合字符串長度語義無符號范圍更大。String(String)和operator(String)移動語義可避免深拷貝開銷是 C11 后必備技能。c_str()提供與 C 庫交互的標準接口。append()替代cat()STLstd::string命名慣例降低學(xué)習(xí)成本。3.2 關(guān)鍵函數(shù)實現(xiàn)防御式編程與異常安全String.cpp中的核心實現(xiàn)必須處理所有邊界// src/String.cpp #include include/String.h #include iostream #include stdexcept // 默認構(gòu)造 String::String() : str(new char[1]), len(0) { str[0] \0; } // C 字符串構(gòu)造處理 nullptr String::String(const char* s) : len(0), str(nullptr) { if (s nullptr) { str new char[1]; str[0] \0; return; } len std::strlen(s); str new char[len 1]; std::strcpy(str, s); } // 拷貝構(gòu)造 String::String(const String other) : len(other.len) { str new char[len 1]; std::strcpy(str, other.str); } // 移動構(gòu)造 String::String(String other) noexcept : str(other.str), len(other.len) { other.str nullptr; other.len 0; } // 析構(gòu) String::~String() { delete[] str; } // 拷貝賦值三步法 String String::operator(const String other) { if (this other) return *this; delete[] str; len other.len; str new char[len 1]; std::strcpy(str, other.str); return *this; } // 移動賦值 String String::operator(String other) noexcept { if (this other) return *this; delete[] str; str other.str; len other.len; other.str nullptr; other.len 0; return *this; } // 連接先擴容再 strcat String String::append(const String other) { if (other.len 0) return *this; // 空字符串直接返回 size_t newLen len other.len; char* newStr new char[newLen 1]; // 復(fù)制原字符串 std::strcpy(newStr, str); // 追加 other 字符串 std::strcat(newStr, other.str); delete[] str; str newStr; len newLen; return *this; } // 友元輸出 std::ostream operator(std::ostream os, const String s) { os s.str; return os; } // 友元輸入安全讀取避免緩沖區(qū)溢出 std::istream operator(std::istream is, String s) { const size_t MAX_INPUT 1024; char buffer[MAX_INPUT]; is.getline(buffer, MAX_INPUT); // 讀取一行自動處理 \n if (is.gcount() MAX_INPUT - 1 is.peek() ! \n) { // 輸入超長清空剩余 is.clear(); is.ignore(10000, \n); } s String(buffer); // 調(diào)用拷貝賦值 return is; }血淚經(jīng)驗總結(jié)String(const char* s)必須檢查s nullptr。C 中向strlen(nullptr)傳參是未定義行為UB程序可能立即崩潰。append()原始cat()直接strcat(str,st.str)是定時炸彈。正確做法是new一塊足夠大的新內(nèi)存strcpystrcat再delete[]舊內(nèi)存。這是 RAIIResource Acquisition Is Initialization思想的樸素體現(xiàn)資源生命周期與對象綁定。operator用getline()替代get()并檢查gcount()判斷是否讀滿緩沖區(qū)再ignore()清理杜絕輸入攻擊。3.3 主函數(shù)測試驗證所有路徑main.cpp應(yīng)覆蓋所有構(gòu)造、賦值、連接場景// src/main_string.cpp #include include/String.h #include iostream int main() { // 測試 1字面量構(gòu)造 String s 吉林大學(xué); std::cout s \ s \, len s.length() std::endl; // 測試 2拷貝構(gòu)造 String t s; std::cout t \ t \ (copy of s) std::endl; // 測試 3默認構(gòu)造 賦值 String m; m t; std::cout m \ m \ (assigned from t) std::endl; // 測試 4append 連接 String a 軟件學(xué)院; m.append(a); std::cout m.append(a) \ m \ std::endl; // 測試 5移動語義C11 String tmp 臨時對象; String moved std::move(tmp); std::cout moved \ moved \, tmp.len tmp.length() std::endl; // 測試 6輸入 std::cout 請輸入新字符串: ; String userInput; std::cin userInput; std::cout userInput \ userInput \ std::endl; return 0; }編譯運行g(shù) -stdc11 -Wall -Wextra -Werror -o string src/String.cpp src/main_string.cpp ./string4. 繼承體系Camera/Chip與多態(tài)工資系統(tǒng)訪問控制與抽象基類的實戰(zhàn)C 和 D 部分是面向?qū)ο笤O(shè)計的“高階考場”。C 部分通過Camera→Chip→Car_camera_*的三級繼承強制你理解public/protected/private繼承對派生類接口的塑造力D 部分用Employee抽象基類和四類雇員讓你親手寫出第一個真正的多態(tài)系統(tǒng)。原始代碼中Car_camera_two的options()調(diào)用Chip::options()會失敗protected成員在類外不可見D 部分的SalariedEmployee多重繼承Employee和Birthdate導(dǎo)致菱形繼承歧義且CalculateSalary()未聲明為virtual破壞多態(tài)。4.1 繼承實驗public/protected/private 的訪問邊界可視化原始Camera.cpp中Car_camera_twoprotected繼承試圖在main()中調(diào)用b.options()但options()在Chip中是publicprotected繼承后在Car_camera_two外部不可見。我們必須用類內(nèi)函數(shù)橋接// include/Camera.h #ifndef CAMERA_H_ #define CAMERA_H_ #include iostream #include string class Camera { protected: // 關(guān)鍵take_photo 改為 protected供派生類使用 virtual void take_photo() { std::cout 攝像功能啟動 std::endl; } public: void image_set() { std::cout 圖像質(zhì)量設(shè)定功能啟動 std::endl; } virtual ~Camera() default; // 虛析構(gòu)確保多態(tài)刪除安全 }; class Chip : public Camera { // Chip 公共繼承 Camera protected: bool menu; double speed; public: Chip() : menu(false), speed(0.0) {} void options() { std::cout 進入操作菜單功能請選擇 std::endl; } void show() const { std::cout 當前車速為 speed std::endl; } void Resetmenu(bool v) { menu v; } }; // 三種繼承方式的行車記錄儀 class Car_camera_one : public Chip { // public 繼承所有 public 成員對外可見 public: void open() { std::cout 行車記錄儀啟動 std::endl; } void close() { std::cout 行車記錄儀關(guān)閉Bye std::endl; } // 可直接使用 Chip::options() 和 Camera::image_set() }; class Car_camera_two : protected Chip { // protected 繼承Chip 的 public 變成 protected public: void open() { std::cout 行車記錄儀啟動 std::endl; } void close() { std::cout 行車記錄儀關(guān)閉Bye std::endl; } // 提供 public 接口來暴露需要的功能 void use_options() { options(); } // 在類內(nèi)調(diào)用合法 void use_image_set() { image_set(); } // Camera::image_set() 是 publicprotected 繼承后仍為 protected但可在派生類內(nèi)調(diào)用 }; class Car_camera_three : private Chip { // private 繼承所有成員變?yōu)?private public: void open() { std::cout 行車記錄儀啟動 std::endl; } void close() { std::cout 行車記錄儀關(guān)閉Bye std::endl; } void use_options() { options(); } // 同樣類內(nèi)可調(diào)用 }; #endif // CAMERA_H_關(guān)鍵修正點Camera::take_photo()改為protectedpublic方法被protected/private繼承后外部無法調(diào)用但派生類內(nèi)部需要它所以設(shè)為protected。Car_camera_two::use_options()protected繼承后options()對main()不可見但Car_camera_two類內(nèi)可調(diào)用因此提供use_options()作為門面。virtual ~Camera() default虛析構(gòu)是多態(tài)刪除的基石。若delete ptr_to_Chip沒有虛析構(gòu)Camera部分不會被正確析構(gòu)。4.2 工資系統(tǒng)抽象基類、多態(tài)與容器管理D 部分原始代碼最大問題是Employee未聲明為抽象基類virtual函數(shù)未 0且SalariedEmployee等類未重寫CalculateSalary()為virtual導(dǎo)致vectorEmployee*中調(diào)用的是基類空實現(xiàn)。此外Birthdate應(yīng)作為Employee的成員而非多重繼承避免菱形問題。重構(gòu)后的Employee體系include/Employee.h// include/Employee.h #ifndef EMPLOYEE_H_ #define EMPLOYEE_H_ #include iostream #include string #include vector #include memory // 用智能指針管理 // 日期類作為 Employee 成員 class Date { public: int year, month, day; Date(int y 1970, int m 1, int d 1) : year(y), month(m), day(d) {} bool isBirthdayThisMonth(int currentMonth) const { return month currentMonth; } }; // 抽象基類 class Employee { protected: std::string m_name; int m_id; Date birthDate; public: Employee(const std::string name, int id, const Date bd) : m_name(name), m_id(id), birthDate(bd) {} // 純虛函數(shù)強制派生類實現(xiàn) virtual double CalculateSalary(int currentMonth) 0; virtual void Output(int currentMonth) 0; virtual ~Employee() default; // 虛析構(gòu) }; // 周薪雇員 class SalariedEmployee : public Employee { private: double weeklySalary; public: SalariedEmployee(const std::string name, int id, const Date bd, double salary) : Employee(name, id, bd), weeklySalary(salary) {} double CalculateSalary(int currentMonth) override { double base weeklySalary; if (birthDate.isBirthdayThisMonth(currentMonth)) { base 100.0; } return base; } void Output(int currentMonth) override { std::cout 員工類型: 周薪雇員 | 姓名: m_name | 工號: m_id | 工資: CalculateSalary(currentMonth) std::endl; } }; // 時薪雇員簡化版僅示意多態(tài) class HourlyEmployee : public Employee { private: double hourlyWage; int hoursWorked; public: HourlyEmployee(const std::string name, int id, const Date bd, double wage, int hours) : Employee(name, id, bd), hourlyWage(wage), hoursWorked(hours) {} double CalculateSalary(int currentMonth) override { double base (hoursWorked 40) ? hoursWorked * hourlyWage : 40 * hourlyWage (hoursWorked - 40) * hourlyWage * 1.5; if (birthDate.isBirthdayThisMonth(currentMonth)) { base 100.0; } return base; } void Output(int currentMonth) override { std::cout 員工類型: 時薪雇員 | 姓名: m_name | 工號: m_id | 工資: CalculateSalary(currentMonth) std::endl; } }; // 容器管理類 class Company { private: std::vectorstd::unique_ptrEmployee employees; public: void addEmployee(std::unique_ptrEmployee emp) { employees.push_back(std::move(emp)); } void payRoll(int currentMonth) { std::cout \n 本月工資發(fā)放 std::endl; for (const auto emp : employees) { emp-Output(currentMonth); } } }; #endif // EMPLOYEE_H_核心改進Employee是純抽象類CalculateSalary()和Output()均為0無法實例化。override關(guān)鍵字顯本文還有配套的精品資源點擊獲取