天天看点

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