C++的引用类型应用实例

引用时变量的别名,可以像变量一样赋值,也可将其用于运算表达式。请看下面测试程序代码:

#include <iostream>
using namespace std;
int t1;
int &t2 = t1;

int main()
{
	t1 = 1000;
	cout << t2 << endl;
	t2++;
	cout << t1 << endl;
}

直接执行的结果如下:

 t2是t1的引用,或者说t2是t1的别名,改变t1的值,实际上就是改变t2的值,改变t2的值也就是改变t1的值,或者说是改变同一内存区间的值。在上面程序中再加一行代码,如下:

#include <iostream>
using namespace std;
int t1;
int &t2 = t1;

int main()
{
	t1 = 1000;
	cout << t2 << endl;
	t2++;
	cout << t1 << endl;
	cout << t1*5 << endl;
	cout << t2 * 10 << endl;

}

直接执行的结果如下:

 可以看出引用也可像变量一样使用。在上面程序中再加一行代码,如下:

#include <iostream>
using namespace std;
int t1;
int &t2 = t1;

int main()
{
	t1 = 1000;
	cout << t2 << endl;
	t2++;
	cout << t1 << endl;
	cout << t1*5 << endl;
	cout << t2 * 10 << endl;
	cout << &t1 << endl;
}

直接执行的结果如下:

 在上面程序中再加一行代码,如下:

#include <iostream>
using namespace std;
int t1;
int &t2 = t1;

int main()
{
	t1 = 1000;
	cout << t2 << endl;
	t2++;
	cout << t1 << endl;
	cout << t1*5 << endl;
	cout << t2 * 10 << endl;
	cout << &t1 << endl;
	cout << &t2 << endl;
}

直接执行的程序结果会怎样呢?结果如下:

 对t1与t2取地址,结果指像同一地址。已定义了变量,再去搞个引用似乎意义不大,像上面这样使用确实有点多此一举。请再看下面程序:

#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
	int tem = x;
	x = y;
	y = tem;
}
int main()
{
	t1 = 1000;
	t2 = 2000;
	swap(t1, t2);
	cout << t1 << endl;
	cout << t2 << endl;
}

直接执行的结果如下:

 没法实现t1、t2值的交换,因为C函数是按值传递,即传递的是变量的值,并不传递变量的地址,没法改变变量的值。再在上面的程序中加一个交换函数swap1,代码如下:

#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
	int tem = x;
	x = y;
	y = tem;
}
void swap1(int &x, int &y)
{
	int tem = x;
	x = y;
	y = tem;
}
int main()
{
	t1 = 1000;
	t2 = 2000;
	swap(t1, t2);
	cout << t1 << endl;
	cout << t2 << endl;
	swap1(t1, t2);
	cout << t1 << endl;
	cout << t2 << endl;
}

直接执行的结果如下:

 调用函数swap1实现了t1、t2值的交换。再在上面的程序中加一个交换函数swap2,代码如下:

#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
	int tem = x;
	x = y;
	y = tem;
}
void swap1(int &x, int &y)
{
	int tem = x;
	x = y;
	y = tem;
}
void swap2(int *x, int *y)
{
	int tem = *x;
	*x = *y;
	*y = tem;
}
int main()
{
	t1 = 1000;
	t2 = 2000;
	swap(t1, t2);
	cout << t1 << endl;
	cout << t2 << endl;
	cout << endl;
	swap1(t1, t2);
	cout << t1 << endl;
	cout << t2 << endl;
	cout << endl;
	swap2(&t1, &t2);
	cout << t1 << endl;
	cout << t2 << endl;
	cout << endl;
}

直接执行的结果如下:

 可以看出交换函数swap2也可实现数据交换,swap1函数参数使用了引用,swap2函数参数使用了指针。swap2函数较swap1函数要复杂得多。引用也实现了变量地址传递,个人感觉函数定义时要实现地址传递,又不想使用指针,就得使用引用,这就是引用类型的最大用处。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bill66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值