C++:引用

基本使用

作用:给变量起别名
语法:数据类型 &别名 =原名 (有点类似指针的感觉)

#include <iostream>
#include <ctime>
#include <string>//c++中字符串需要添加这个头文件
using namespace std;

int main()
{
	int a = 88;
	int &b = a;
	cout << a << endl;
	cout << b << endl;

	b = 20;
	cout << a << endl;
	cout << b << endl;
	system("pause");
	return 0;
}

在这里插入图片描述

注意事项

1.引用必须初始化
2.初始化之后就不可被改变了

#include <iostream>
#include <ctime>
#include <string>//c++中字符串需要添加这个头文件
using namespace std;

int main()
{
	int a = 88;
	int &b = a;
	int &c;
	system("pause");
	return 0;
}

在这里插入图片描述

引用做函数参数

作用:函数传参数时,可以利用引用的技术让形参修饰实参
有点:可以简化指针修改实参

#include <iostream>
#include <ctime>
#include <string>//c++中字符串需要添加这个头文件
using namespace std;

void swap1(int, int);
void swap2(int *, int *);
void swap3(int &, int &);
int main()
{
	int a = 22, b = 33;
	cout << "未修改:" << "a=" << a << " " << "b=" << b << endl;

	swap1(a, b);
	cout << "普通交换:" << "a=" << a << " " << "b=" << b << endl;
	swap2(&a, &b);
	cout << "指针交换:" << "a=" << a << " " << "b=" << b << endl;
	swap3(a, b);
	cout << "引用交换:" << "a=" << a << " " << "b=" << b << endl;

	system("pause");
	return 0;
}

void swap1(int x, int y)
{
	int temp = x;
	x = y;
	y = temp;
}
void swap2(int *x, int *y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}
void swap3(int &x, int &y)
{
	int temp = x;
	x = y;
	y = temp;
}

在这里插入图片描述

引用作函数的返回值

  • 不要返回局部变量
  • 函数的调用可以作为左值
    在这里插入图片描述第一次正确,是因为编译器做了保留
    在这里插入图片描述
    Static变量是在全局区 等待程序运行完后才会释放
    在这里插入图片描述
    函数的返回是一个引用 那么函数可以作为一个左值

引用的本质

本质:引用的本质在C++内部实现是一个指针常量
指针常量 int * const p:指向不可以修改 指针指向的值可以修改
C++推荐使用引用计数 因为语法简单
在这里插入图片描述

常量引用

作用:修饰形参 防止误操作
在这里插入图片描述

#include <iostream>
#include <ctime>
#include <string>//c++中字符串需要添加这个头文件
using namespace std;

void show(int & c)
{
	c = 100;
	cout << c << endl;
}

int main()
{
	int a = 10;

	show(a);
	cout << a << endl;
	system("pause");
	return 0;
}
输出结果都是100

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_LiuChunJiang刘春江

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

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

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

打赏作者

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

抵扣说明:

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

余额充值