天天看點

c++中什麼是引用,什麼是指針。

引用就是引用位址,給變量取個小名,這個都可以改變變量的數值。
代碼:
#include <iostream>
  
 using namespace std;
  
 int main ()
 {
    // 聲明簡單的變量
    int    i;
    double d;
  
    // 聲明引用變量
    int&    r = i;
    double& s = d;
    
    i = 5;
    cout << "Value of i : " << i << endl;
    cout << "Value of i reference : " << r  << endl;
  
    d = 11.7;
    cout << "Value of d : " << d << endl;
    cout << "Value of d reference : " << s  << endl;
    
    return 0;
 } 
結果::
 
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
 
 
指針也是一種存儲,隻不過存的是位址,用*取取出位址所對應的數值:
上代碼:
#include <iostream>
  
 using namespace std;
  
 int main ()
 {
    int  var = 20;   // 實際變量的聲明
    int  *ip;        // 指針變量的聲明
  
    ip = &var;       // 在指針變量中存儲 var 的位址
  
    cout << "Value of var variable: ";
    cout << var << endl;
  
    // 輸出在指針變量中存儲的位址
    cout << "Address stored in ip variable: ";
    cout << ip << endl;
  
    // 通路指針中位址的值
    cout << "Value of *ip variable: ";
    cout << *ip << endl;
  
    return 0;
 } 
代碼結果:
 
Value of var variable: 20
Address stored in ip variable: 0x7fff5bfda1d8
Value of *ip variable: 20