[重修] 計算機程式-7 & 8 Pointers and Strings I, II
這裡開始講到重點了, 以前沒觀念不夠清楚的地方 剛剛好一次性複習.
首先為什麼要用 pointer,
在高級語言中,指標有效的取代了在低階語言(如組合語言與機器碼)直接使用記憶體位址。但它可能只適用於合法位址之中。因為指標更貼近硬體,編譯器能夠很容易的將指標翻譯為機器碼,這使指標操作時的負擔較少,因此能夠提高程式的運作速度。
使用指標能夠簡化許多資料結構的實作,例如在遍歷字串,查取表格,控制表格及樹狀結構上。對指標進行複製,之後再解參照指標以取出資料,無論在時間或空間上,都比直接複製及存取資料本身來的經濟快速。指標表示法較為直覺,使程式的表達更為簡潔,同時也能夠提供動態機制來建立新的節點。
在程式編程(procedural programming)中,指標也被用來儲存系統呼叫流程,以及動態連結資料庫(DLL)的進入點位址。在物件導向編程中,使用函式指標(Function pointer)來綁定方法(method),常見於虛擬方法表(Virtual method table)中。
接者重點整理,
1) pointer只能 assign 0, NULL, 跟 address.
2) 下面這個例子ok嗎? 答案是ok的, 因為這裡的 "&" 是 reference.
int a = 10;
int &b = a;
3) pointer 容易讓人搞不清楚的原因是,
a. 宣告跟使用是不同的意思.
int *p = &a; <=== 宣告一個指標p, 指向a的位置
cout << *p; <=== 使用, 這裡 *p 等於 a
b. pointer 跟 function 使用的多種寫法, 讓人混淆
目前有三種傳法,
- pass-by-value
- pass-by-reference
- pass-by-reference with pointer
其中 pass-by-reference 跟 pass-by-pointer 速度應該是一樣的. 只不過pass-by-reference比較好寫(程式碼簡潔).
4) 四種 const with pointer
- Non-constant pointer to non-constant data (兩者都可變)
int *aptr;
- Non-constant point to constant data ( 指標所指向的內容是常量不可變)
const int *aptr;
- Constant pointer to non-constant data (指針本身是常量不可變)
int * const aptr = &a;
- Constant pointer to constant data (兩者都不可變)
const int * const aprt = &a;
還有其中區別方法:
沿著*號劃一條線,
如果const位於*的左側,則const就是用來修飾指標所指向的變數,即指標指向為常量;
如果const位於*的右側,const就是修飾指標本身,即指標本身是常量。
5) Array name 本身就是pointer. 屬於 Constant pointer to constant data
6) 指標與 array
line_7 跟 line_9 做的事情是一樣的. 所以輸出的值在這相同.
7) sizeof函數
如果sizeof data type 就一定要括號
cout << sizeof( int );
如果sizeof 變數就不一定
int i = 3;
cout << sizeof i;
8) function pointer
要理解函數指標, 還是需要多看看例子.
更多例子,關於為什麼要用函數指標, 越大的專案用function pointer越好. 因為可以讓程式 維護性更高.(可讀性降低)
Function pointers can be useful when you want to create callback mechanism, and need to pass address of an function to another function. They can also be useful when you want to store an array of functions, to call dynamically for example. One common use is to implement a callback function (Callback 即call then back 被主函式呼叫運算後會返回主函式)
function pointer也蠻常跟typedef一起用的.
留言
張貼留言