Reference vs. pointer

前端 未结 6 561
终归单人心
终归单人心 2020-12-28 08:33

What is the difference? Because this:

int Value = 50;
int *pValue = &Value;

*pValue = 88;

and ref version do the same:



        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 09:18

    The differences are:

    Reference is an alias of an object and has the same address as the object.

    int a;         //  address of   a : 0x0012AB
    int &ref = a;  //  address of ref : 0x0012AB (the same)
    

    References must be initialized :

    int &ref = a; // GOOD, is compiling
    int &ref;     // BAd, is not compiling
    

    Pointer is another variable that holds an address:

    int a = 5;     //  address of a : 0x0012AB 
    int *p = &a;   //  address of p : 0x0012AF (is different )
    
    // value of a is 5
    // value of p is 0x0012AB  (address of a)
    

    Pointers can be NULL

    int *p = NULL;
    

提交回复
热议问题