在 C++ 開發中,MFC(Microsoft Foundation Classes)與 STL(Standard Template Library)容器的混合使用是許多 Windows 桌面應用開發者必須面對的課題。本文整理自一個典型的課程作業實戰,系統梳理了從專案配置、頭文件管理、類設計、檔案 I/O 到演算法應用的完整知識體系,助你避開常見坑點,寫出健壯、可維護的程式碼。
核心任務:讀取兩個成績檔案(grade.txt、grade2.txt),分別使用 MFC 容器(CArray、CList、CMap)與 STL 容器(vector、list、queue、map)完成資料存儲、輸出、排序與刪除操作,最終結果寫入 學號_result.txt。
現象: 使用 MFC 容器類時,若專案未正確配置 MFC 支援,鏈接階段報 error LNK2001。
解決方案:
原理:MFC 容器類實現在 MFC DLL 中,必須正確鏈接 MFC 執行庫。
MFC(舊式頭文件 .h 後綴)與 STL(標準頭文件無後綴)混用易引發符號衝突。採用模組化頭文件策略:
// MFCData.h
#include // CObject, CString 等基礎類
#include // CArray, CList, CMap 等模板類
#include // 舊式 I/O
#include // C 風格字串處理
#include // 舊式檔案流
// STLData.h
#include // 標準檔案流
#include // 標準 I/O 流
#include // std::string
#include // sort 等演算法
#include
#include
#include
#include
核心原則: 每個容器類別對應獨立的 .h/.cpp,將 MFC 與 STL 實現物理隔離,從源頭消除符號汙染。
針對兩種資料格式(有/無綽號),採用繼承體系:
class cSwordsman {
protected:
CString id, name;
int score;
public:
// 建構子、存取器、虛擬輸出函式
virtual void FileOut(ofstream& fout);
virtual void ScreenOut();
// 運算子重載支援 STL 演算法
BOOL operator<(cSwordsman& y);
BOOL operator>(cSwordsman& y);
BOOL operator==(cSwordsman& y);
};
class cLongSwordsman : public cSwordsman {
protected:
CString moniker;
public:
// 擴充建構子、moniker 存取器
void FileOut(ofstream& fout) override; // 重載父類輸出
void ScreenOut() override;
};
設計亮點:
protected 成員讓派生類直接訪問基類資料,減少存取器呼叫開銷。operator< 使 std::sort、std::map 等演算法開箱即用。FileOut/ScreenOut 實現多型輸出,統一介面處理不同容器。關鍵技巧: 以 ofstream& 引用傳遞檔案流,避免重複開關檔案:
void cSwordsman::FileOut(ofstream& fout) {
fout << id << ' ' << name << ' ' << score << endl;
}
新舊標準流差異表:
| 特性 | <fstream.h> (舊) | <fstream> (新) |
|---|---|---|
| 開啟模式 | ios::in | ios::nocreate | ios_base::in |
getline | getline(buf, len) | getline(stream, string) |
| 命名空間 | 全域 | std:: |
cSwordsman 與 cLongSwordsman,減少命名負擔。operator< 直通 std::sort、std::map 排序鍵比較。ifstream fin("grade.txt") 像 cin 一樣用 >> 讀取;複雜行解析用 getline + 字串分割。vector/list/queue:it->member 或 (*it).func()map:it->first (key)、it->second (value),呼叫成員函式用 it->second.func()map 的 pair 結構MFC 與 STL 的共存不是對立,而是互補。MFC 容器深度整合 Windows 資源管理,STL 容器提供標準化、高效能的演算法支援。掌握模組化封裝、介面導向設計、標準庫演算法複用,才是驾駭雙重生態系統的關鍵。下次面對類似需求,請記住:隔離邊界、統一介面、複用演算法。