(C++学习笔记三)引用

五.引用

1.代码 :


#include<iostream>
using namespace std;//C++标准名称空间 


//值传递
void Swap_z(int a,int b)//这种传递方式不能交换两数的值
{
	int num = a;
	a = b;
	b = num;
}

//地址传递
void Swap_d(int* a, int* b)
{
	int num = *a;
	*a = *b;
	*b = num;
}

//引用传递
void Swap_y(int &a, int &b)
{
	int num = a;
	a = b;
	b = num;
}

//返回局部变量引用 warring :
int& test_j(void)
{
	int a = 10;
	return a;
}

//返回静态变量引用
int& test_t(void)
{
	static int a = 2020;
	return a;
}

void test_1(int& re)
{
	re = 138;//re 是引用,转化为 *re = 138;
}

int main()
{
	int a = 167;

	int &b = a;//引用  给变量起别名

	int c = 22;

	cout << "int &b = a; a = " << a << endl;
	cout << "            b = " << b << endl;

	b = 177;

	cout << "b = 177;    a = " << a << endl;
	cout << "            b = " << b << endl;

	a = 166;

	cout << "a = 166;    a = " << a << endl;
	cout << "            b = " << b << endl << endl;

	a = 11;
	cout << "                a = " << a << endl;
	cout << "                c = " << c << endl;

	Swap_z(a,c);

	cout << "Swap_z(a,c);    a = " << a << endl;
	cout << "                c = " << c << endl;

	Swap_d(&a,&c);
	cout << "Swap_d(&a,&c);  a = " << a << endl;
	cout << "                c = " << c << endl;

	Swap_y(a,c);
	cout << "Swap_d(a,c);    a = " << a << endl;
	cout << "                c = " << c << endl;

/*	//返回局部变量引用
	int& test_j(void)
	{
		int a = 10;
		return a;
	}

	//返回静态变量引用
	int& test_t(void)
	{
		static int a;
		return a;
	}

	void test_1(int& re)
	{
		re = 138;//re 是引用,转化为 *re = 138;
	}
	*/
	cout << " 引用与左值 " << endl;

	int& ref = test_j();//警告:返回局部变量或返回局部变量地址
	cout << "int& ref = " << ref << endl;
	cout << "int& ref = " << ref << endl;

	int& ref1 = test_t();//如果函数做左值,那么必须返回引用
	cout << "int& ref1 = " << ref1 << endl;
	cout << "int& ref1 = " << ref1 << endl;

	test_t() = 1001;//函数做左值

	cout << "test_t() = 1001; ref1 = " << ref1 << endl;
	cout << "test_t() = 1001; ref1 = " << ref1 << endl;

	a = 10;

	cout << endl << " 引用的本质 " << endl;
	
	int& re = a;

	//自动转换为 int* const re = &a;
	//引用的 本质 在C++内部实现是一个指针常量
	//指针常量是指针指向不可改,也说明了为什么 引用 不可改

	re = 20;//内部发现 re 是引用,自动转为:*re = 20;

	cout << " a = " << a << endl
		 << "re = " << re << endl;

	cout << endl << " 常量引用 " << endl;

	//int& re1 = 16;// Error 
	const int re1 = 16;

	//系统优化: int temp = 16; const int& rel = temp;
	//rel 为常量

	cout << "re1 = " << re1 << endl;

	system("pause");
	return 0;
}

2.运行结果 :

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值