C++中新增了一种新的复合类型,引用变量。引用变量是已定义变量的另一个名字(注意仅仅是名字变了)。引用变量主要用来当做函数的形参,这样在函数调用时就会省去值传递的过程,直接使用原始数据。
引用的基本用法如下所示:
int cola;
int &happyWater=cola;
在这里&并不是地址运算符。这里&与int组合成为一个新的标识符:int &,指该变量是一个int变量的引用。为了进一步验证cola与happyWater的关系,可以由代码进行观察它们的内容与地址:
#include <iostream>
int main()
{
using namespace std;
int cola=3;
int &happyWater=cola;
cout<<"the value of cola:"<<cola<<endl;//打印cola的内容
cout<<"the address of cola:"<<&cola<<endl;//打印cola的地址
cout<<"the value of happyWater:"<<happyWater<<endl;//打印happyWater的内容
cout<<"the address of happyWater:"<<&happyWater<<endl;//打印happyWater的地址
cin.get();
return 0;
}
代码运行结果如下:
显而易见,cola与其引用变量happyWater完全是一个变量,内容与地址一模一样,使用起来完全等效。在代码中稍作改动,令其中一个值变化,来验证结论:
#include <iostream>
int main()
{
using namespace std;
int cola=3;
int &happyWater=cola;
happyWater+=1;//happyWater自增1
cout<<"the value of cola:"<<cola<<endl;
cout<<"the address of cola:"<<&cola<<endl;
cout<<"the value of happyWater:"<<happyWater<<endl;
cout<<"the address of happyWater:"<<&happyWater<<endl;
cin.get();
return 0;
}
代码运行结果如下:
自此引用变量的用法与性质已经非常清晰。
用法:定义时使用基本变量+&进行定义,定义的同时必须赋值;定义完成后按基本变量使用即可。
性质:单纯地为一个变量的别名,引用变量与原始变量可以平等对待。
问题回到结构体函数中来,由于有些结构体内容较多,采用值传递的方法在函数中进行调用不太合适,因此这里为结构体创建引用变量,将其作为形参,这样在函数调用的时候可以直接对原始结构体进行使用。
由刚刚总结的引用变量的用法可知,只需要定义时稍作修改即可,那么原先的原型函数头应该修改为以下形式:
exampleStructure sum(const exampleStructure &a,const exampleStructure &b)
修改后的结构体函数中a与b作为函数的引用变量,而不是普通的参量,这样在调用时可以直接使用结构体A与B。同时需要注意,如果不需要修改结构体的内容,建议在声明前加const进行保护,当函数试图修改引用变量时编译器将自动报错。
修改后的整体代码如下:
#include <iostream>
struct exampleStructure
{
int variable1;
int variable2;
};
exampleStructure sum(const exampleStructure &a,const exampleStructure &b);
int main()
{
using namespace std;
exampleStructure A={12,13};//结构体变量A
exampleStructure B={14,15};//结构体变量B
exampleStructure addNum=sum(A,B);
cout<<"total variable1:"<<addNum.variable1<<endl;//打印出variable1的和
cout<<"total variable2:"<<addNum.variable2<<endl;//打印出variable2的和
cin.get();//按一个按键后退出
return 0;
}
exampleStructure sum(const exampleStructure &a,const exampleStructure &b)
{
exampleStructure total;
total.variable1=a.variable1+b.variable1;
total.variable2=a.variable2+b.variable2;
return total;
}
运行结果如下图:
自此,C++中结构体函数的三种形式已经介绍完毕。该三种方式分别为:
1.值传递返回型,特点:直观,不适合处理数据多的结构体。
2.结构体指针型,特点:传递地址,资源开销小。
3.引用变量型,特点:直接使用原始数据,资源开销小,是C++中的时髦操作。