【C++】引用

引用的基本语法

语法:数据类型 &别名 = 变量名
作用:给变量起别名

#include<iostream>
using namespace std;

int main() {

	//int& a;//定义时就必须初始化,所有此时会报错
	int a = 10;
	cout << a << endl;

	int& x = a;//给变量a起别名
	x = 100;//改变引用指向内容的值

	cout << a << endl;
	cout << x << endl;

	return 0;
}

引用注意事项

#include<iostream>
using namespace std;

int& func() {
	int a = 10;
	return a;
}


int main() {
	int& x = func();
	cout << x << endl;//输出:10
	cout << x << endl;//输出:2047785360 此时的变量内容已经被系统回收
	return 0;
}
  • 不要将局部变量用引用给函数返回赋值给变量,因为此时返回出来的变量的值在使用一次后就会被系统回收

引用做函数参数

#include<iostream>
using namespace std;
//值传递
void swap01(int a, int b) {
	int temp;
	temp = a;
	a = b;
	b = temp;
}
//地址传递
void swap02(int* a, int* b) {
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}
//引用传递
void swap03(int& a, int& b) {
	int temp;
	temp = a;
	a = b;
	b = temp;
}

int main() {

	int a = 10;
	int b = 20;
	
	swap01(a, b);
	cout << "a=" << a << " b=" <<b<< endl;
	
	swap02(&a, &b);
	cout << "a=" << a << " b=" <<b<< endl;

	swap03(a, b);
	cout << "a=" << a << " b=" <<b<< endl;

	return 0;

}

引用做函数的返回值

#include<iostream>
using namespace std;

int& func() {
	int a = 10;
	return a;
}

int main() {

	int& ref = func();
	cout << ref << endl;
	//函数左值
	func() = 1000;
	cout << ref << endl;
	return 0;
}

引用的本质

#include<iostream>
using namespace std;
void func(int& x) {
	x = 100;
}

int main() {
	int a = 10;
	int& ref = a;//自动转换为 int* const ref = &a; 指针常量的指向不可变,也就解释了为什么引用的指向也不可变
	ref = 20;//自动转换为 *ref = 20;
	cout << "a=" << a << " ref=" << ref << endl;
	
	func(a);
	cout << "a=" << a << " ref=" << ref << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值