指針和引用的比較

Comparing Pointers and References
指針和引用的比較

While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers. The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object.

雖然使用引用(reference)和指針都可間接訪問另一個值,但它們之間有兩個重要區別。第一個區別在於引用總是指向某個對象:定義引用時沒有初始化是錯誤的。第二個重要區別則是賦值行爲的差異:給引用賦值修改的是該引用所關聯的對象的值,而並不是使引用與另一個對象關聯。引用一經初始化,就始終指向同一個特定對象(這就是爲什麼引用必須在定義時初始化的原因)。

 

1

 

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int a = 1024;
    int *pi =&a; 
    int **ppi = &pi;
   
    cout << a <<"/n"     //輸出1024
         << *pi<<"/n"   //輸出1024
         << *ppi       //輸出一個內存地址
         << **ppe     //輸出1024 
    system("pause");
   
    return EXIT_SUCCESS;
}

 

 

C++ 使用 ** 操作符指派一個指針指向另一指針。這些對象可表示爲:

 

ppi 進行解引用照常獲得 ppi 所指的對象,在本例中,所獲得的對象是指向 int 型變量的指針 pi

          int *pi2 = *ppi; // ppi points to a pointer

To actually access ival, we need to dereference ppi twice:

爲了真正地訪問到 ival 對象,必須對 ppi 進行兩次解引用。

 

 

2

 

在表達式中使用數組名時,該名字會自動轉換爲指向數組第一個元素的指針:

          int ia[] = {0,2,4,6,8};
          int *ip = ia; // ip points to ia[0]

如果希望使指針指向數組中的另一個元素,則可使用下標操作符給某個元素定位,然後用取地址操作符 & 獲取該元素的存儲地址:

          ip = &ia[4];    // ip points to last element in ia
使用指針的算術操作在指向數組某個元素的指針上加上(或減去)一個整型數值,就可以計算出指向數組另一元素的指針值:
          ip = ia;            // ok: ip points to ia[0]
          int *ip2 = ip + 4;  // ok: ip2 points to ia[4], the last element in ia

When we add 4 to the pointer ip, we are computing a new pointer. That new pointer points to the element four elements further on in the array from the one to which ip currently points.

在指針 ip 上加 4 得到一個新的指針,指向數組中 ip 當前指向的元素後的第 4 個元素。

More generally, when we add (or subtract) an integral value to a pointer, the effect is to compute a new pointer. The new pointer points to the element as many elements as that integral value ahead of (or behind) the original pointer.

通常,在指針上加上(或減去)一個整型數值 n 等效於獲得一個新指針,該新指針指向指針原來指向的元素之後(或之前)的第 n 個元素。

Pointer arithmetic is legal only if the original pointer and the newly calculated pointer address elements of the same array or an element one past the end of that array. If we have a pointer to an object, we can also compute a pointer that points just after that object by adding one to the pointer.

指針的算術操作只有在原指針和計算出來的新指針都指向同一個數組的元素,或指向該數組存儲空間的下一單元時纔是合法的。如果指針指向一對象,我們還可以在指針上加1從而獲取指向相鄰的下一個對象的指針。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章