c++新特性---引用变量
一、定义
引用变量是已定义变量的别名,如将ra设置为a的引用变量,则可以使用ra和a交替使用该变量。
表示:
int a = 5;
int & ra = a;
其中&不是地址运算符,而是类型标示符的一部分。
二、含义
使用引用变量ra和变量a都指向同一个地址,都可以改变变量的值。
三、引用变量和指针的区别
int a = 100;
int & ra = a; //ra a reference
int * pa = &a; //pa a pointer
1、表示法不同:
表达式ra和*pa都可以和a交换,而表达式&ra和pa都可以和&a交换。
2、初始化不同:
引用变量必须在声明时初始化
int a;
int & ra = a;
指针可以先声明,再初始化
int a;
int * pa;
pa = &a;
四、应用
1、可以通过初始化设置引用,不可以通过赋值设置:
int A = 2;
int & a = A;
cout << "A = " << A << ",a = " << a << endl;
cout << "A adress = " << &A << ",a address = " << &a << endl;
int b = 3;
a = b;
cout << "A = " << A << ",a = " << a << ",b = " << b << endl;
cout << "A adress = " << &A << ",a address = " << &a << ",b address = " << &b << endl;
——————程序运行结果——————
A = 2,a = 2
A adress = 0x22fef8,a address = 0x22fef8
A = 3,a = 3,b = 3
A adress = 0x22fef8,a address = 0x22fef8,b address = 0x22fef4
由上可知,a = b,等同于A = b;结果是a和A的值都变成了3,但是两个变量的地址没变,说明不可以通过赋值设置引用变量,一旦初始化设置了就不可以改变。
2、将引用用作函数参数:
void swapv(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}
void swapp(int * m, int * n){
int temp;
temp = *m;
*m = *n;
*n = temp;
}
void swapr(int & m, int & n){
int temp;
temp = m;
m = n;
n = temp;
}
int a = 2;
int b = 6;
swapv(a, b);
cout << "use value " << "a = " << a << ", b = " << b << endl;
swapp(&a, &b);
cout << "use pointer " << "a = " << a << ", b = " << b << endl;
swapr(a, b);
cout << "use reference chang again " << "a = " << a << ", b = " << b << endl;
——————程序运行结果——————
use value a = 2, b = 6
use pointer a = 6, b = 2
use reference chang again a = 2, b = 6
由上可知,只有指针和引用变量可以交换数据,赋值方式不可。