引用变量是c++的复合类型,引用是已定义变量的别名。引用变量的主要用途是用作函数的形参。通过将它作为参数,函数将使用原始数据,而不是副本,这样除指针外,引用也为函数处理大型结构提供一个方便的途径,同样对于设计类来说,引用也是必不可少的。
1 引用变量
int people = 20;
int & persons = people; //1)
int * human = &people; // 2)
int * const ps = &people; // 3)
cout << "ad of people:" << &people <<",value:" << people << endl;
cout << "ad of persons:" << &persons << ",value:" << persons << endl;
int folk = 50;
persons = folk; //4)
cout << "ad of people:" << &people <<",value:" << people << endl;
cout << "ad of persons:" << &persons << ",value:" << persons << endl;
cout << "ad of folk:" << &folk << ",value:" << folk << endl;
people = 20;
int * pt = &people;
int &per = *pt; // per是一个指向int的引用,不是指向pt的引用
pt = & folk; // 5)
cout << "ad of people:" << &people <<",value:" << people << endl;
cout << "ad of folk:" << &folk << ",value:" << folk << endl;
cout << "ad of pt:" << pt << ",value:" << *pt << endl;
cout << "ad of per:" << &per << ",value:" << per << endl;
// 输出结果
ad of people:0x6ffdf4,value:20
ad of persons:0x6ffdf4,value:20
ad of people:0x6ffdf4,value:50
ad of persons:0x6ffdf4,value:50
ad of folk:0x6ffdf0,value:50
ad of people: