## 重載、前置處理、其他...
### 12/1 社課
----
因為剛段考完
而且下禮拜迷你馬
今天就上輕鬆一點的東西
---
## 重載
----
同樣名稱的函式
只要形式(參數型別、數量...)不同
就可以算是不同的函式
----
拿起一個栗子
```cpp=
int func(int a, int b){
return a+b;
}
long long func(long long a, long long b){
return a*b;
}
```
這兩個是不同的函式
----
```cpp=
int func(int a, int b){
return a+b;
}
long long func(long long a, long long b){
return a*b;
}
int main(){
int a=3, b=3;
long long c=3, d=3;
cout << func(a, b) << ' ' << func(c, d);
}
```
```
6 9
```
---
## 運算子重載
----
運算子其實也算另類的函式(?
相同的運算子兩邊放不同的東西
也是重載的一種
```cpp=
int a, b;
long long c, d;
// a+b -> int
// a+c -> long long
// c+d -> long long
```
----
我們之前學過
```cpp=
struct st{
//...
type operator +(...){
//...
}
}
```
----
宣告運算子規則
```cpp=
type operator 符號(type a, type b){
//...
}
```
```cpp=
pair<int, int> operator +(pair<int ,int> p, int x){
return {p.first+x, p.second+x};
}
int main(){
pair<int, int> p={2, 3};
p=p+1; // {3, 4}
}
```
---
## 前置處理
----
程式編譯的過程其實是
原始碼$\rightarrow$經過前置處理器$\rightarrow$修改後的程式碼
$\rightarrow$經過編譯器$\rightarrow$執行檔
----
C++中的 \# 井字號都屬於前置處理
像是
- #include
- #define
- #if
----
### include
各位應該對它很熟悉吧
我們需要引入標頭檔才能使用某些語法
而 include 就是用來引入檔案的
它可以把一個檔案的文字複製貼上
----
test.txt
```
cout << "Hello World" << '\n';
```
hello.cpp
```cpp=
#include<iostream>
using namespace std;
int main(){
#include"test.txt"
}
```
----
經過前置處理後
```cpp=
/* <iostream> 裡的東西*/
using namespace std;
int main(){
cout << "Hello World" << '\n';
}
```
----
#include <...>
從 lib 中找檔案
#include "..."
從相同目錄中找檔案
----
### define
定義
就是用某些字去替代原來的東西
----
### 範例
```cpp=
#include<bits/stdc++.h>
#define a 2
using namespace std;
int main(){
cout << a << '\n';
}
```
----
### 常用時機
```cpp=
#define pii pair<int, int>
#define F first
#define S second
#define mp make_pair
#define pb push_back
```
----
可以用 #undef a 解除對 a 的 define
---
## 在函式中宣告函式
----
### 語法
----
方法一
```cpp=
function<回傳型別(參數們的型別)> name=[&](參數們){
//...
};
```
----
方法二
```cpp=
auto name=[&](參數們)->回傳型別{
//...
};
```
----
```cpp=
int main(){
function<int(int)> func=[&](int x){ // 方法一
return x*2;
};
auto func2=[&](int a, int b)->int{ // 方法二
return a+b;
};
cout << func(1) << ' ' << func2(1, 2);
}
```
```
2 3
```
----
其實不是很重要
優點:可以使用區域變數
缺點:你要多背一個東西
{"description":"type: slides","contributors":"[{\"id\":\"1a0296c8-ce58-4742-acda-22c02ae81a74\",\"add\":2358,\"del\":8}]","title":"12/01 C++社課"}