c++引用

霸气de小男生 提交于 2019-11-30 06:30:21

首先我们知道任何变量都有左值和右值,分别对应变量的内存区域和内存区域中的值

引用其实就是变量的别名,其实是一个东西有两个名吧

定义方式 类型 &引用名 = 变量名 而且必须定义的时候就初始化,不然是错误的

看个例子吧

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int i = 9;
 7     int *p = &i;
 8     int &ir = i;
 9     cout << &i << " " << &ir << " " << p << endl;
10     
11     cout << i << " " << *p << " " << ir << endl;
12     cout << &i << " " << &ir << " " << p << endl;
13     
14     *p = 3;
15     cout << i << " " << *p << " " << ir << endl;
16     cout << &i << " " << &ir << " " << p << endl;
17     
18     ir = 8;
19     cout << i << " " << *p << " " << ir << endl;
20     cout << &i << " " << &ir << " " << p << endl;
21     
22     i = 99;
23     cout << i << " " << *p << " " << ir << endl;
24     cout << &i << " " << &ir << " " << p << endl;
25     
26     int *p2 = &ir;
27     cout << i << " " << *p << " " << ir << " " << *p2 << endl;
28     
29     *p2 = 666;
30     cout << &i << " " << &ir << " " << p << " " << p2 << endl;
31     cout << i << " " << *p << " " << ir << " " << *p2 << endl;
32     cout << &i << " " << &ir << " " << p << " " << p2 << endl;
33     return 0;
34 } 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!