c++引用
Posted mch5201314
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++引用相关的知识,希望对你有一定的参考价值。
首先我们知道任何变量都有左值和右值,分别对应变量的内存区域和内存区域中的值
引用其实就是变量的别名,其实是一个东西有两个名吧
定义方式 类型 &引用名 = 变量名 而且必须定义的时候就初始化,不然是错误的
看个例子吧
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++引用的主要内容,如果未能解决你的问题,请参考以下文章