说明:
1、引用即为为某变量定义一个别名,其内存和地址都是相同的。
2、当用于函数时,引用可以使用函数参数,从而返回函数值。
1示例:
#include <iostream>
using namespace std;
int main()
{
int i = 10;
int &j = i;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
if (&j == &i)
{
cout << "i 和 j地址相同" << endl;
}
}
运行结果:
2示例:
#include <iostream>
using namespace std;
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
int a[] = {1, 3, 5, 7, 9};
int& index(int i)
{
return a[i];
}
int main()
{
int a = 5, b = 10;
//交换数字a和b
swap(a, b);
cout << "a = " << a << " b = " << b << endl;
cout << index(2) << endl; //等价于输出元素a[2]的值
index(2) = 100; //等价于将a[2]的值赋为100;
cout << index(2) << endl;
return 0;
}