引用的基本概念
给变量起别名
规则
1 引用没有定义,是一种关系型声明。声明它和原有某一变量(实体)的关
系。故 而类型与原类型保持一致,且不分配内存。与被引用的变量有相同的地
址。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include<iostream>
using namespace std;
int main(int argc, char* argv[]) { int a = 100;
int & re = a;
cout << "&a = " << &a << endl; cout << "&re = " << &re << endl;
return 0; }
|

2 声明的时候必须初始化,一经声明,不可变更。
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include<iostream>
using namespace std;
int main(int argc, char* argv[]) { int a = 100; int &re = a; cout << re << endl;
return 0; }
|
3 可对引用,再次引用。多次引用的结果,是某一变量具有多个别名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include<iostream>
using namespace std;
int main(int argc, char* argv[]) { int a = 100; int &re = a; int &re2 = re; cout << re << endl; cout << re2 << endl; cout << &a << endl; cout << &re << endl; cout << &re2 << endl;
return 0; }
|
4 &符号前有数据类型时,是引用。其它皆为取地址。
引用做函数参数或函数返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include<iostream>
using namespace std;
typedef struct student { char name[50]; float score; int sex; }Student;
int my_swap(int &a, int &b) { int tem = a; a = b; b = tem; return 0; }
Student & my_print(Student &a) { cout << a.name << endl; cout << a.score << endl; cout << a.sex << endl;
return a; }
int main(int argc, char* argv[]) { Student XiaoMing = { "XiaoMing",100.0f,1 };
int a = 100, b = 90;
cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "--------------------------------" << endl; my_swap(a, b); my_print(XiaoMing); cout << "--------------------------------" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl;
return 0; }
|