# Week 2 ###### tags: `C++` ## Week 1 複習 ### 字元(char) vs 字串(string) 字元: * 使用ASCII編碼 * 單引號'' 字串: * 數個字元組成的字元陣列 ### int? long long? int => 省空間,較快 比賽不會卡,直接把int當long long用 ```cpp! #define int long long ``` ## Function ### 為什麼要有函式 * 避免冗長程式碼 * 可以重複呼叫 * 增加可讀性 * 遞迴的實作 ### 函式宣告 ```cpp int add(int a, int b){ int sum = a + b; return sum; } ``` > int: 傳回值型態 > add: 函式名稱 > int a: 引數型別,引數名稱 ### 範例 #### void:無回傳值 ```cpp= void print(int x){ cout << x << endl; } int main(){ print(5); print(4); print(3); } ``` #### 多載:不同引數型態 ```cpp= void print(int a) { cout << "int: " << a << endl; } void print(string s) { cout << "string: " << s << endl; } int main() { print(5); // int: 5 print("haha"); // string: haha } ``` #### 預設引數 ```cpp= void print(int a = 5) { // 若未給定a,將預設為5。 cout << "int: " << a << endl; } int main() { print(); print(10); } ``` #### call by reference 給變數別名 ```cpp= int a = 5; int &b = a; // b為int reference型別 b = 10; // a也跟著變成10 cout << a << ' ' << b << endl; ``` ## struct 結構 ```cpp struct student { string name, student_id; int art_score, pe_score; }; ``` > struct: 關鍵字 > student: 新型態的名稱 > { }內:結構成員 :::warning 要以分號結束結構樣板的宣告 ::: 使用「.」提取student結構裡的成員,如: ```cpp= struct student { string name, student_id; int art_score, pe_score; } student a; a[i].student_id; //提取student_id ``` 宣告: 1. 一個一個給值 2. 依順序給 > 可以將結構視為自定義的型別 ### Struct中新增method 建構子:宣告此結構會執行的函式 ```cpp= struct student { int art_score, pe_score; int sum; student(int a, int b) : art_score(a), pe_score(b) { sum = a + b; } }; int main() { student a(5, 100); cout << a.sum << endl; } ``` ### 運算子重載 定義運算子功能 #### 加法 使用operator+可以定義加號的操作 自定義相加要怎麼相加 #### 比大小 operator #### 排序
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up