码迷,mamicode.com
首页 > 编程语言 > 详细

c++引用

时间:2019-09-22 20:00:35      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:初始化   左值   方式   using   ret   必须   space   别名   技术   

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

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

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

看个例子吧

 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 } 

技术图片

 

c++引用

标签:初始化   左值   方式   using   ret   必须   space   别名   技术   

原文地址:https://www.cnblogs.com/mch5201314/p/11568699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!