Dev-C++ 雖然是 lightweight 的 IDE,但用來練習 C++ 類別編程綽綽有餘。以下把從建工程到跑通的每一步寫清楚,其中有一個環節特別容易漏掉,會直接導致鏈接錯誤。
打開 Dev-C++ 後,依序點選 File -> New -> Project,在彈出的視窗中選擇 Console Application。若要做圖形介面程式,則改選 Windows Application。
工程建好後按 Ctrl+N 新增檔案。這一步務必選擇「添加到工程」(在提示視窗中選 Yes),否則編譯會出現鏈接錯誤——我親身試過,缺了這步就找不到函數實現。
一個帶類別的工程,至少應該有 main.cpp、xxx.cpp 與 xxx.h 三個檔案,其中 xxx 為類別檔名。介面與實現分離的好處很直接:使用方只需包含頭檔,不必知道內部細節。
main.cpp 的內容如下:
// main.cpp
#include <iostream>
#include "demo.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
demo foo1(0);
foo1.show();
return 1;
}
這裡 return 1 只是沿用 Dev-C++ 產生的樣板,按慣例 main 正常結束應回傳 0。另外 Dev-C++ 的 Console Application 預設會在終端機暫停等待按鍵,若使用自己的 getch 或 input loop,記得把樣板裡的 pause 機制移除,避免多停一次。
demo.h 中放類別聲明與成員函數原型,demo.cpp 中放實現,三者齊備後按 F11 編譯運行即可看到輸出。