# 類別 (Class) --- ## 1. 物件導向程式設計 ## 2. 定義新的變數型態 ###### (幾乎算是啦...) --- ## 基本宣告及架構 ---- ```cpp= class 類別名稱{ public: 資料型態 變數名稱1; 資料型態 變數名稱2; // 資料成員 (Data Member) 傳回值型態 函數名稱1(引數1, 引數2, 引數3 ...){ 函數內容; return 傳回值; } 傳回值型態 函數名稱2(引數1, 引數2, 引數3 ...){ 函數內容; return 傳回值; } // 成員函數 (Member Function) };// 要加分號 ``` ---- ```cpp= #include <iostream> using namespace std; class grade{ public: int eng, chi, math, sci, soc; double avg(void){ double sum = 0; sum += eng+chi+math+sci+soc; return sum/5; } void setup(void){ cin>>chi>>eng>>math>>soc>>sci; return; } }; int main(){ grade student1, student2; student1.setup(); // 輸入 99, 98, 97, 96, 95 student2.setup(); // 輸入 95, 94, 93, 92, 91 cout<<student1.avg()<<endl; // 輸出 97 cout<<student2.avg()<<endl; // 輸出 93 cout<<student1.math<<' '<<student2.math<<endl; // 輸出 97 93 return 0; } ``` --- ### 建構元 ``` 類別名稱(){ 設定內容; } ``` ### 解構元 ``` ~類別名稱(){ 設定內容; } ``` ---- ```cpp= #include <iostream> using namespace std; class grade{ public: int sum; int eng, chi, math, sci, soc; grade(){ sum = 0; cout<<"Class setting...\n"; } double avg(void){ double sum += eng+chi+math+sci+soc; return sum/5; } void setup(void){ cin>>chi>>eng>>math>>soc>>sci; return; } }; int main(){ grade student1, student2; // 輸出 Class setting... // 輸出 Class setting... student1.setup(); // 輸入 99, 98, 97, 96, 95 student2.setup(); // 輸入 95, 94, 93, 92, 91 cout<<student1.avg()<<endl; // 輸出 97 cout<<student2.avg()<<endl; // 輸出 93 cout<<student1.math<<' '<<student2.math<<endl; // 輸出 97 93 return 0; } ``` ---- ```cpp= //#include<stdio.h> //#include<stdlib.h> #include<bits/stdc++.h> #define endl '\n' using namespace std; class node{ private: int num; node *next; public: node(){ num = 0; next = nullptr; } node(int key){ num = key; next = nullptr; } friend class LIST; }; class LIST{ private: node *root; void add(int key, node *cur){ if(root == nullptr){ node *nextnode = new node(); nextnode->num = key; root = nextnode; } else{ if(bool(cur->next)) add(key, cur->next); else{ node *nextnode = new node(); nextnode->num = key; cur->next = nextnode; } } } void destruct(node *cur){ if(root == nullptr) return; else{ if(bool(cur->next)) destruct(cur->next); delete cur->next; cur->next = nullptr; } } public: LIST(){ root = nullptr; } ~LIST(){ destruct(root); root = nullptr; } void push(int key){ add(key, root); } void clear(void){ destruct(root); root = nullptr; } }; int main(){ cin.tie(nullptr); //ios_base::sync_with_stdio(false); LIST vec; for(int k=0;k<100;k++) vec.push(k); vec.clear(); return 0; } ```
{"metaMigratedAt":"2023-06-15T00:18:26.539Z","metaMigratedFrom":"Content","title":"類別 (Class)","breaks":true,"contributors":"[{\"id\":\"e5cad38d-b128-4a77-9e0d-d53dea367946\",\"add\":3808,\"del\":594}]"}
    273 views