Thursday, April 19, 2012

Reference in C++

Reference : A simple reference datatype that is less powerful but safer than the pointer type inherited form C. (from Wiki)

Comparing to "Pointers"
  1. It's not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references. (cannot be "reseated", which is often done with pointers) 
    • 在初次定義過後不能再指向其他物件(但pointer常常被用來做這件事情),故命名中會表達所指向的物件為何。
  2. References cannot be "null", whereas pointers can. (Note, containers of references are not allowed)
    • reference不能存「空」的值,也表示,一個「裝references」的容器是不被允許的。
  3. References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created.
    • 基於reference一定要在初次定義時候初始化(分配指向的物件),所以沒有「重新初始化」或是「消去初始值」類的東西。
Things About References
  1. [運作]不論上述三項目的不同之外,References與Pointer都是用「傳位址」的方法實現。
    • 當作函數參數值時,函數改變該參數內容,原本呼叫函數的地方,該參數對應的變數,值也會被更改。
    • 非「傳值」的方式,所以沒有傳送太大資料量的問題。
  2. [使用]作為函式傳入值使用的時候:
    • 呼叫函式的地方值用一般變數方法:int square( x, result ); // int result, int x=3;
    • 接傳入值的函數定義處要加"&":int square( int x, int &result ) {}
    • 函式內部使用該傳入值時,用一般變數的方法:result = x*x;