0.引用概述
引用 :一个东西的两种叫法。是一种漂亮的指针。
从编译器实现的角度看:引用在编译器中是通过指针实现的。
object和reference的大小相同,地址也相同(全都是假象)
注意:
1、sizeof(r) == sizeof(x)
2、&x == &r
示例代码:
#include<iostream>
using namespace std;
//referecce
//object和reference的大小相同,地址也相同(全都是假象)
typedef struct Stag { int a, b, c, d; } S;
int main()
{
S s;
S& rs = s;
cout << sizeof(s) << endl; //16
cout << sizeof(rs) << endl;//16
cout << &s << endl; //003AFD7C
cout << &rs << endl; //003AFD7C
}
在实际的使用中:
reference通常不用于声名变量。
而用于
参数类型(parameters type)和返回类型(return type)的描述。
使用reference的调用接口很好,示例伪代码如下:
//调用接口相同,很好
void func1(Cla* pobj) { pobj->xxx();}
void func2(Cla pobj) { pobj.xxx(); }
void func3(Cla& pobj) { pobj.xxx(); }
...
Cla obj;
func1(&obj); --接口不同,不太好
func2(obj); --调用接口相同,很好
func3(obj); --调用接口相同,很好
一、引用作为函数参数
1、程序员能够修改调用函数中的数据对象。
2、通过传递引用而不是整个数据对象,可以提高程序的运行速度。
当数据对象较大时(如结构和类对象),第二个原因最重要。
应用一:用于内置类型int
实现数据交换的功能。void swapr(int & a, int & b) // use references
{
int temp;
temp = a; // use a, b for values of variables
a = b;
b = temp;
}
void swapp(int * p, int * q) // 使用指针同样可以完成
{
int temp;
temp = *p; // use *p, *q for values of variables
*p = *q;
*q = temp;
}
引用的调用为:swap(x,y);
指针的调用为:swap(&x,&y);
应用二:用于结构体对象和类对象
(1)这里要对结构体内部的内容进行修改,只能使用引用参数或者指针参数,不能按值传递。
void set_pc(free_throws & ft)
{
if (ft.attempts != 0)
ft.percent = 100.0f *float(ft.made)/float(ft.attempts);
else
ft.percent = 0;
}
(2)由于不修改内部的参数,因此函数使用一个const引用参数。
void display(const free_throws & ft)
{
using std::cout;
cout << "Name: " << ft.name << '\n';
cout << " Made: " << ft.made << '\t';
cout << "Attempts: " << ft.attempts << '\t';
cout << "Percent: " << ft.percent << '\n';
}
二、引用作为函数返回值
返回引用,要求在函数的参数中,包含有以引用方式或指针方式存在的,需要被返回的参数。
1、如果返回值不做左值,返回结果设置为const reference。如果需要做左值,则不加const限定。
int& abc(int a, int b, int c, int& result)
{
result = a + b + c;
return result;
}
如果传入的参数为指针:
int& abc(int a, int b, int c, int *result)
{
*result = a + b + c;
return *result;
}
2、不能返回局部对象的引用。对局部对象的引用会指向不确定的内存。