void test(){ int a = 10; //ra是一个引用,ra是a的别名 int& ra = a; A sa; sa.a = 1; sa.b = 1; //引用不分配新的空间 A& rsa = sa; //拷贝会分配新的空间 A copy = sa; copy.a = 5; //不会印象sa中的变量 rsa.a = 10; //会印象sa中的变量 }
void test1(){ //引用必须初始化 int a = 10; //变量有多个引用 int& ra = a; int& ra1 = a; int& ra2 = a; //都可以改变a的值 ra = 5; ra1 = 10; ra2 = 20; a = 30; }
void test2(){ //常引用:引用指向的实体不能修改 const int a = 10; const int& ra = a; double d = 2.5; int c = 10; c = d; const int& ra3 = d; }
//交换函数 //指针 void Swap(int* a, int* b){ int tmp = *a; *a = *b; *b = tmp; } //引用 void Swap(int& a, int& b){ int tmp = a; a = b; b = tmp; }
//返回值引用 int& add(int& a, int& b){ return a += b; } void test3(){ int a = 10; int b = 20; int& ra = add(a, b); //ra=30,a=30,b=20 }