CPP基礎.Lesson 4
多維陣列
什麼是維???!
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
維度 |
對應到… |
零維 |
int a |
一維 |
int a[10] |
二維 |
int a[10][10] |
… |
… |
宣告多維陣列
輸入陣列的值 (宜搭配for服用)
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
注意!
- 索引值從0開始
- 索引值只能是整數
- 也可以用變數當索引
- 讀到記憶體外就會RE吃到飽
陣列不能互相指定,比較
一維或多維都是
修飾子 Qualifier
資料型態
- 變數的儲存方式
- 不同型態的變數所占大小不同
- bit? byte?
8 bits = 1 byte
Mbps
和 MB/s
不一樣喔!
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
型別 |
意義 |
bool |
boolean值(真值) |
char |
字元 |
int |
整數 |
float |
浮點數 |
double |
倍準浮點數 |
修飾什麼?
宣告額外性質
<climits>, <limits>
可以取得各型態範圍
空間大小: (sizeof(xxx) 回傳 xxx 所佔據的位元組數)
C 與 C++ 標準皆沒有規範大小,
大多要看編譯時電腦的 CPU 架構與作業系統而定
型別 |
32-bit Windows |
64-bit Windows |
64-bit MacOS/linux |
short int |
16 bits = 2 bytes |
16 bits = 2 bytes |
16 bits = 2 bytes |
int |
32 bits = 4 bytes |
32 bits = 4 bytes |
32 bits = 4 bytes |
long int |
32 bits = 4 bytes |
32 bits = 4 bytes |
64 bits = 8 bytes |
long long int |
64 bits = 8 bytes |
64 bits = 8 bytes |
64 bits = 8 bytes |
const
const: constant(不變的)的簡寫,有翻譯作常量
顧名思義,初始化後就不可再更改
必須在編譯時初始化
目的是要預防寫程式的人不小心寫錯
常用來修飾參數,可以預防函數使壞
static
static: 靜態的
生命周期(下面會提到)不隨函數消長(整支程式永遠恰有一個)
可以想成:變數範圍不變、生命週期變為整個程式碼
另外,static 變數不能被其他 C++ 檔案使用
例如在標頭檔中宣告的 static 全域變數
在引入這個標頭檔的 cpp 檔中是無法使用(看不到)這個變數的
其他修飾子
- C++: extern, inline, volatile
- C: register, restrict, _Atomic…
總結
- short, long, unsigned 可以修飾資料型態
- const 可以避免意外修改
- static 可以讓變數一直活著
- 參考資料很雜,但放 cppreference 準沒錯
Struct
假設…你是個車輛經銷商
- 儲存車輛的資料
- 價格
- 年份
- 長、寬、高(體積)
- 油耗量
- 最高時數
- ….
solution 1
開好幾條陣列
solution 2
開一條二維陣列
- 不夠直觀,無法直接從Index中判斷資料類型
- 不能同時把不同類型的東西綁一起
使用struct
宣告
Scope
變數的生命週期
變數活著的時候我們可以使用
死後無人知曉無影無蹤
Local Variables
活在block裡的變數
在block裡宣告 (出生)
出block就死亡
Block
block: 被大括號包起來的區域
Global Variables
可以在程式的各個角落使用他
通常宣告在程式的頂部
在block, function 外
全域變數每個地方都可以改
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
出bug機率大如果區域變數的名稱跟全域變數相同
- 編譯會過? 會
- 那用誰的? 優先使用最後命名的
namespace
如果今天你要和一堆人一起寫project
為了避免撞名,該怎麼辦?
using namespace [namespace]
所有在[namespace]的名稱都可以使用
回家作業
d626: 小畫家真好用